Table of Contents
In this post we will explore Functions in C. We will look at what functions are and how they make our lives easy.
Let’s say in your program you want to do something multiple times at different places. If the action is of just a single line or two, you can write them wherever you need them. But, think for a moment that it requires 15 lines. What happens when you have to write these 15 lines everywhere? A lot of problems crop up:
- The code becomes huge. Same 15 lines being used at multiple places
- Maintaining it becomes very difficult. Any change in logic will require you to make the changes everywhere. Also, there are high chances that you might miss making the changes at some places.
- Debugging it becomes difficult.
Considering the above describes scenario, wouldn’t it be better if we could avoid writing the same set of statements again and again? Avoid writing again and again but keeping the functionality intact?
That is where functions come into picture. What we can do is take these 15 statements, group them together enclosed by { } and give this set a name. This entire set is called a function and the name is called the function name.
For example: Consider these below set of statements. Imagine having to write them at 10 different places in your program.
int avgTemp = 0; avgTemp = (temperature1 + temperature2 + temperature3 + temperature4 + temperature5 + temperature6)/6; printf("The average temperature is %d\n",avgTemp); if(avgTemp > 30) { printf("It is too hot\n"); } else if(avgTemp<=30 && avgTemp > 10) { printf("It is moderate\n"); } else { printf("It is too cold\n"); }
Instead, what you can do is to group them together and give them a name as shown below. We have taken all the statements from above, grouped them and given a name calAvgTemp()
void calAvgTemp() { int avgTemp = 0; avgTemp = (temperature1 + temperature2 + temperature3 + temperature4 + temperature5 + temperature6)/6; printf("The average temperature is %d\n",avgTemp); if(avgTemp > 30) { printf("It is too hot\n"); } else if(avgTemp<=30 && avgTemp > 10) { printf("It is moderate\n"); } else { printf("It is too cold\n"); } }
Now, wherever we need these lines, we can just use the function name there. There are many benefits as you can already guess:
- Your code size reduces
- Easier to maintain. Any change in logic will require you to change at only one place
- Debugging is easier
Every C program has at least one function, which is main().You can divide up your code into separate functions. How you divide up your code among different functions is up to you, but logically the division is such that each function performs a specific task.
A function declaration tells the compiler about a function’s name, return type, and parameters. A function definition provides the actual body of the function.
The C standard library provides numerous built-in functions that your program can call. For example, strcat() to concatenate two strings, memcpy() to copy one memory location to another location, or, printf() to print a statement.
Types of Functions in C
There are two types of function in C programming:
- Standard library functions
- User-defined functions
Let’s see them one by one.
Standard library functions
The standard library functions are built-in functions in C programming.
These functions are defined in header files. For example,
- The
printf()
is a standard library function to send formatted output to the screen (display output on the screen). This function is defined in thestdio.h
header file.
Hence, to use theprintf()
function, we need to include thestdio.h
header file using#include <stdio.h>
. - The
sqrt()
function calculates the square root of a number. The function is defined in themath.h
header file.
There are many other library functions in C. However, we are not discussion library functions in details in this post.
User-defined functions
As we saw in the beginning of this post, we can create our own functions. Such functions are called user-defined functions.
How user-defined function works?
#include <stdio.h> void functionName() { ... .. ... ... .. ... } int main() { ... .. ... ... .. ... functionName(); ... .. ... ... .. ... }
The execution of a C program begins from the main()
function.
When the compiler encounters functionName();
, control of the program jumps to
void functionName()
And, the compiler starts executing the codes inside functionName()
.
The control of the program jumps back to the main()
function once code inside the function definition is executed.
Note, function names are identifiers and should be unique.
Here is an example to add two integers. To perform this task, we have created an user-defined addNumbers()
.
#include <stdio.h> int addNumbers(int a, int b); // function prototype int main() { int n1,n2,sum; printf("Enters two numbers: "); scanf("%d %d",&n1,&n2); sum = addNumbers(n1, n2); // function call printf("sum = %d",sum); return 0; } int addNumbers(int a, int b) // function definition { int result; result = a+b; return result; // return statement }
Function prototype
A function prototype is simply the declaration of a function that specifies function’s name, parameters and return type. It doesn’t contain function body.
A function prototype gives information to the compiler that the function may later be used in the program.
Syntax of function prototype
returnType functionName(type1 argument1, type2 argument2, ...);
In the above example, int addNumbers(int a, int b);
is the function prototype which provides the following information to the compiler:
- name of the function is
addNumbers()
- return type of the function is
int
- two arguments of type
int
are passed to the function
We don’t need a function prototype if we define the function before the main()
function. However, it is always a good practice to do so.
Calling Functions in C
Control of the program is transferred to the user-defined function by calling it.
Syntax of function call
functionName(argument1, argument2, ...);
In the above example, the function call is made using addNumbers(n1, n2);
statement inside the main()
function.
Function definition
Function definition contains the block of code to perform a specific task. In our example, adding two numbers and returning it.
Syntax of function definition
returnType functionName(type1 argument1, type2 argument2, ...) { //body of the function }
When a function is called, the control of the program is transferred to the function definition. And, the compiler starts executing the codes inside the body of a function.
Passing arguments to Functions in C
In programming, argument refers to the variable passed to the function. In the above example, two variables n1 and n2 are passed during the function call. These parameters are called actual arguments.
The parameters a and b accepts the passed arguments in the function definition. These arguments are called formal parameters of the function or formal arguments.
The type of arguments passed to a function and the formal parameters must match, otherwise, the compiler will throw an error.
If n1 is of char type, a also should be of char type. If n2 is of float type, variable b also should be of float type.
A function can also be called without passing an argument.
Return Statement
The return statement terminates the execution of a function and returns a value to the calling function. The program control is transferred to the calling function after the return statement.
In the above example, the value of the result variable is returned to the main function. The sum variable in the main()
function is assigned this value.
Syntax of return statement
return (expression);
For example,
return a; return (a+b);
Note: – The type of value returned from the function and the return type specified in the function prototype and function definition must match.
Important Points about Functions in C:
Following are some important points related to functions in C.
- Function name must be unique
- Keywords cannot be used as function names
- The type of value returned from the function and the return type specified in the function prototype and function definition must match.
- The number of arguments in a function and a function call must match
- The types of arguments in a function and a function call must match
Functions can be further classified based on the return types and arguments. We will look into those in the subsequent post.
Vivek is a Senior Embedded Innovation Specialist. He has been working on Embedded Systems for the past 10 years. He loves to share his knowledge and train those who are interested. Nerdyelectronics.com was started out of this interest.