Ways of Calling Function : C Programming
We have summarized different ways of calling C functions -
[crosslist]
- Call function using Separate Programming Statement
- Calling Function from Expression.
- Inline Function Calling
#include<stdio.h> int add(int,int); int main() { int sum,num1,num2; num1 = 10; num2 = 20; sum = add(num1,num2); printf("Sum is : %d",sum); return 0; } int add(int n1,int n2) { return (n1+n2); }
Explanation :
sum = add(num1,num2);[arrowlist]
- Call Function by using function name followed by parameter list enclosed in angular brackets and followed by semicolon.
- We have occupied 1 statement for this function call.
- If function is going to return a value then we should preserve returned value.
- To preserve a value we call function and assign function call to any variable. (in above example)
sum = a + add(num1,num2) + c ;
Example :
[arrowlist]
- Suppose we have to add 4 numbers say a,b,num1,num2.
- We are adding num1 and num2 using function.
[arrowlist]
- We have function call as part of expression.
- No need to use semicolon after function call.
#include<stdio.h> int add(int,int); int main() { int sum,num1,num2; num1 = 10; num2 = 20; printf("Sum is : %d",add(num1,num2)); return 0; } int Add(int n1,int n2) { return (n1+n2); }
Explanation :
[arrowlist]
- We can directly call function from printf statement.
printf("Sum is : %d",add(num1,num2));
How this printf gets executed -
- Firstly we are going to call function add.
- add() function will return result of the type integer as its return type specified is Integer.
- Returned Result will be displayed in printf statement.