Function in C
Function is a group of statements that are used to perform any task. In other words, we can say that a function is a self- contained a block of programs that perform a coherent task. Why to use function A function is used to divide a large code into modules that help us to debug and maintain the code. We can call any function multiple times. There are various advantages of function:
- Code re-usability
- Easy to debug the program
- Code optimization.
- Library Function :
- User-defined function
return typefunction name( parameter list ) { body of the function }The function definition consists of a function header and a function body. There are the following parts of a function.
- Return type: A function may return a value. If we don’t want to return a value then we have to use void.
- Function name: We can define the function name.
- Parameters: We can pass the value in function at the time of calling.
- Function body: Function body is the collection of statements.
#include <stdio.h> void sum(); // declaring a function int a=5,b=10, c; void sum() // defining function { c=a*b; printf("Multiplication of (A*B) : %d\n", c); } int main() { sum(); // calling function return 0; }Output
Multiplication of (A*B) : 50Call by value and call by Reference in C In C language, there are two ways to pass the value of data to function.
- call by value.
- call by reference.
Call by value:
We can’t change the original value at the time of passing value in the function but it can be changed for the current function only. It will not change the value of a variable inside the caller method such as main().
Let us consider an example:
Call by reference:
We can change the original value while using call by reference through pass the reference (address).
#include<stdio.h> void abc(int id, int mob) { printf(" Passing value inside the abc function"); } int main() { int id=101, mob=90972762; abc(id, mob); // passing value to the function printf("\nValue of ID: %d",id); printf("\nValue of NAME: %d",mob); return 0; }Output
Passing value inside the abc function Value of ID: 101 Value of NAME: 90972762
Let us consider an example:
#include <stdio.h> void fun(int *n) { printf("Adding value before inside the function=%d \n",*n); (*n) += 10; printf("Adding value after inside the function=%d \n", *n); } int main() { int x=10; printf("Before function call x=%d \n", x); fun(&x);//passing reference in function printf("After function call x=%d \n", x); return 0; }
Output
Before function call x=10 Adding value before inside the function=10 Adding value after inside the function=20 After function call x=20