Function Calling


A function can be called using the name of the function following the list of actual parameters enclosed in parentheses. Example:

int main()
{
  int s;
  s = sum(10,20);
  printf("%d",s);
  return 0;
}

When the compiler encounters a function call, the control is transferred to function sum (). This function is performed line by line as described and a value is returned when a return statement is received. This value is assigned to s. This is illustrated below :

Functions Calling

The function call sends two integer values 10 and 20 to the function.

int sum(int a, int b)

which are assigned to a and b respectively. The function computes summation a and b, assigns the result to the local variable s, and then returns the value 30 to the main where it is assigned to s.

There are many different ways to call a function. Listed below are some of the ways the function sum can be invoked.

sum(10,20);
sum(a,10);
sum(10,b);
sum(a+10,b);
sum(a,b+10);
sum(10,sum(a,b));

Note that the sixth call uses its own call as one of the parameters. When we use expressions, they should be evaluated to single values that can be passed as actual parameters.

A function that returns a value can be used in expressions like any other variable. Each of the following statements is valid :

printf("%d\n",sum(a,b));
s = sum(a,b)/(a+b);
if(sum(a,b)>0)
 printf("large");

However, a function cannot be used on the right side of an assignment statement. For instance,

sum(a,b) = 20;

Note :

  1. If the actual parameters are more than the formal parameters, the extra actual arguments will be discarded.
  2. On the other hand, if the actuals are less than the formals, the unmatched formal arguments will be initialized to some garbage.
  3. Any mismatch in data types may also result in some garbage values.