C calling function examples



We have summarized different ways of calling C functions –
[crosslist]

  • Call function using Separate Programming Statement
  • Calling Function from Expression.
  • Inline Function Calling

[/crosslist]
Way 1 : Call function using Separate Programming Statement

#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)

[/arrowlist]
Way 2 : Calling Function from Expression.

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]
Explanation :
[arrowlist]

  • We have function call as part of expression.
  • No need to use semicolon after function call.

[/arrowlist]
Way 3 : Inline Function Calling

#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.

[/arrowlist]

printf("Sum is : %d",add(num1,num2));

How this printf gets executed¬† –

  1. Firstly we are going to call function add.
  2. add() function will return result of the type integer as its return type specified is Integer.
  3. Returned Result will be displayed in printf statement.