Functions in C

In every programming language, functions are one of the key features available to the programmer. The C programming language also has a bunch of built-in functions. Apart from the built-in functions, we can also define our own function to C.

Functions are very useful to all programming languages. Functions help in code reusability and it is easy to understand the code with functions.

What are functions in C?

In C, we can divide large programs into building blocks which are known as functions.

Suppose, you have a block of code and you want to execute those blocks of code again and again to perform some specific task then you can make use of functions.

Function includes a set of statements enclosed by {}. To provide reusability and modularity to the code, you can call functions multiple times. Standard C library has numerous built-in functions that your program can call.

Advantages of functions in C

  • It provides code reusability and modularity.
  • You can call the provided function from anywhere in your code.
  • Also used to avoid writing the same block of code again and again in the program.
  • With the help of functions, it is easy to understand and analyze the program.

Function aspects in C

  • Function Declaration:- Functions must be declared globally.
  • Function Call:- A function can be called from anywhere in the program.
  • Function Definition:- It includes the statements which are to be executed. But only one value can be returned from the function.
Function Aspects Syntax
Function Declaration return_type function_name (arguments);
Function call function_name (arguments)
Function definition return_type function_name (arguments) {statements;}

Defining a function in C

Syntax of creating function in c programming language:-

return_type function_name(parameter list){  
// body of the function
}

Example of defining C Function

int sum(int n1, int n2){
int final;
final = n1 + n2;
return final;
}

Below are the some parts of a function:-

  • Return Type:- It is the data type of the value that the function returns. Some functions do not return any value. In that case, the return type is void.
  • Function name:– It is the actual name given to the function.
  • Parameters:- When a function is defined, you pass a value to the parameter. It is optional. A function may not contain any parameters.
  • Function Body:- It contains statements that define what the function does.

Types of Functions in C

Two types of functions available in C:-

1. Library Functions:- These functions are declared in C header files like printf(), scanf(), gets(), puts() etc.

2. User-Defined Functions:- In C, you can create your own function. They are known as user-defined functions.

Advantages of user-defined function in C

  • It’s easy to understand and debug the code.
  • Don’t have to use the same block of code again and again.

Working of C User-Defined functions

Execution of the C program starts from the main() function.

#include <stdio.h>
void functionName()
{
// body of the function!
}
int main()
{
... .. ...
... .. ...
functionName();
... .. ...
... .. ...
}

Basic Example of user defined function in C:-

#include <stdio.h>
// function minimum()!
int minimum(int i, int j)
{
if (i < j)
return i;
else
return j;
}
int main(void)
{
int x = 555, y = 69;
printf("TechVidvan Tutorials: Basic Example of C!");
int min = minimum(x, y); // function calling!
printf("m is %d!", min);
return 0;
}

Output

TechVidvan Tutorials: Basic Example of C!
m is 69!

User Defined Function prototype:-

It is generally the declaration of a function that specifies the function’s name, parameters and return type.
Syntax:-
returnType functionName(type1 argument1, type2 argument2, …);

Example:-

int sum_of_numbers(int a, int b);

In the above example, the name of the function is sum_of_numbers, return type is int and two int arguments are passed to the function. If a user defined function is defined before the main() function, then function prototype is not needed.

Calling a function:-

To use the function, you will have to call it first.
Syntax:-
functionName(argument 1, argument 2, …);

User-Defined function definition:-

In C, you can define a block of code as a function to perform a specific task.

Syntax:-

return_type function_name(type1 argument1, type2 argument2, ...)
{
    // function body
}

Function Declarations in C

Function declaration helps the compiler in many ways.

With the help of function declaration, the compiler will know the number of parameters that the function takes, Data types of the parameters, and Return type of the function.

It is optional to put parameter names in function declaration. But you do have to put them in the definition.

Example of Function Declaration

int min(int x, int y);
int max(int, int);
int local(char, int);

It is always a must to declare functions before they are used.

Passing parameters to function in C:-

Parameters passed to the function are known as actual parameters. In the above code, 555 and 69 are actual parameters.

Received parameters by the function are known as formal parameters. In the above code, i and j are formal parameters.

In C, we can use two popular ways to pass parameter:-

1. pass by value

Values of the actual parameters are copied into the function’s formal parameters. And these two types of parameters are stored in different memory locations.

In C, this is the most used passing technique.

For Example:-

#include <stdio.h>
int local(int i)
{
i= 60;
return i;
}
int main()
{
int i= 20;
local(i);
printf("i= %d", i);
return 0;
}

Output

i= 20

2. pass by reference

In this, the actual and formal parameters refer to the same memory locations. To implement it, we have to use pointers.

For Example:-

#include <stdio.h>
int local(int *i)
{
*i=60;
return *i;
}
int main()
{
int i= 20;
local(&i);
printf("i= %d", i);
return 0;
}

Output

i= 60

Function Calling in C

A function contains a block of code which will perform a specific task. You will have to call the function which will perform that specific task.

To call a function, you will have to pass the required parameters and the function name. And if the function returns value then you can store it.

For Example:-

#include <stdio.h>
int sum(int n1, int n2); // function declaration!
int main () {
int num1 = 6;
int num2 = 15;
int final;
final = sum(num1, num2); // function calling!
printf("TechVidvan Tutorials: Basic Example of function calling...\n\n");
printf( "Max value is : %d\n", final );
return 0;
}
int sum(int n1, int n2){ // function to return the sum of two values!
int res;
res = n1 + n2;
return res;
}

Output

TechVidvan Tutorials: Basic Example of function calling…

Max value is : 21

Return Value:-

C function may or may not return a value. If you do not want to return any value then use the void keyword.

Syntax:-

return (expression);

For Example:-

return a;
return (a+b);

Example of a C program that does not return value:-

void final(){  
printf("TechVidvan Tutorials: Example of a C program that does not return value");  
}

And, if you want to return value from the function, then you will have to use the data types like int, float, char, long etc.

Example with return value:-

int sum(){  
return 40;  
} 

In the above, the return type is int. To get the value of the function, you need to call it.

Different aspects of function calling

Four different aspects of function calling:-

  • function without arguments and without return value
  • function without arguments and with return value
  • function with arguments and without return value
  • function with arguments and with return value

Example of function without arguments and return value:-

#include<stdio.h>  
void bestblog();  
int main ()  
{  
bestblog();  
}  
void bestblog()  
{  
printf("Hey, Please Like and Share TechVidvan Tutorials..");  
} 

Output

Hey, Please Like and Share TechVidvan Tutorials..

Example of function without arguments and with return value:-

#include<stdio.h>  
int main()  
{  
float area = square();  
printf("The area of the square: %f\n",area);  
}  
int square()  
{  
float a = 5;  
return a * a;  
}

Output

The area of the square: 25.000000

Example of function with arguments and without return value:-

#include<stdio.h>  
void average(float, float, float, float, float);  
int main()  
{  
float i=1,j=5.2,k=4,l=4,m=1.2;   
average(i,j,k,l,m);  
}  
void average(float i, float j, float k, float l, float m)  
{  
float avg;   
avg = (i+j+k+l+m)/5;
printf("TechVidvan Tutorials: Find Average!\n");
printf("Average is: %f",avg);  
}

Output

TechVidvan Tutorials: Find Average!
Average is: 3.080000

Example of function with arguments and return value:-

#include<stdio.h>  
int checkprime(int);  
void main()  
{  
int a=17,result;  
result = checkprime(a);  
printf("TechVidvan Tutorials: Check Prime or not!\n\n");
if(result == 0)  
{  
printf("The number is odd!");  
}  
else   
{  
printf("The number is even!");  
}  
}  
int checkprime(int a)  
{  
if(a%2 == 0)  
{  
return 1;  
}  
else   
{  
return 0;  
}  
}

Output

TechVidvan Tutorials: Check Prime or not!

The number is odd!

C Library Functions

These functions are the built-in functions in C. These library functions are used to perform some specific task. There are different header files available in C which contain these C library functions. The header files are defined with .h extension. To make use of these library functions, we have to include these header files at the start of our code.

Suppose, you want to use printf() and scanf() functions in your program then you have to include stdio.h in your program.

Below is the table for mostly used header files:-

Header File What it does
stdio.h Contains all the library functions regarding standard input/output.
conio.h  It is a console input/output header file.
string.h Contains all string related functions like gets(), puts() etc.
stdlib.h Contains all the general library functions like malloc(), calloc(), exit() etc.
math.h Contains all math operations related functions like sqrt(), pow() etc.
time.h Contains all time related functions.
ctype.h Contains all character handling functions.
signal.h Contains all signal handling functions.
setjmp.h Contains all jump functions.
locale.h Contains locale functions.
errno.h Contains error handling functions.
assert.h Contains diagnostics functions.
stdarg.h Contains variable argument functions.

Important points about functions in C

  • There has to be a function called main() in every C program.
  • Every C function may or may not return value. If it does not return any value, then the void keyword is used.
  • C function can return any type of data except arrays and functions.
  • In C, a function is called before its declaration. After that the compiler automatically knows that the declaration of function is as:- int functionName();.

Main Function in C

This function is a special one. Every C program must contain a main() function. main() function is the entry point of C programs.

Types of C main function:-

1. main function without parameters:-

int main()
{
   // body
   return 0;
}

2. main function with parameters:-

int main(int argc, char * const argv[])
{
   // body
   return 0;
}

Summary

There are two types of functions present in C such as Library Functions and User-Defined functions. In C, there are various standard library functions available. Also, you can declare your own function. To make use of these library functions, we have to include these header files at the start of our code. To make use of the function, you will have to call it.