Tuesday, December 15, 2009

5.3 ACCESSING A FUNCTION

A function can be accessed (i.e. called) by specifying its name,followed by a list of arguments enclosed in parentheses and separated by commas.If the function call does not require any arguments,an empty pair of parentheses must follow the name of the function.

The arguments appearing in the function call are referred to as actual arguments,in contrast to the formal arguments that appear in the first line of the function definition.(They are also known simply as arguments,or as actual parameters).In a normal function call,there will be one actual argument for each formal argument.Each actual argument must be of the same data type as its corresponding formal argument.Remember that it is the value of each actual argument that is transferred into the function and assigned to the corresponding formal argument.

If the function returns a value,the function access is often written as an assignment statement.e.g

y=polynomial(x);

This function access causes the value returned by the function to be assigned to the variable y.

On the other hand,if the function does not return anything,the function access appears by itself.

e.g display(a,b,c);

This function access causes the value of a,b, and c to be processed internally (i.e. displayed) within the function.

The following program determines the largest of three integer quantities.This program makes use of a function that determines the larger of two integer quantities.

/*determine the largest of three integer quantities*/


#include stdio.h


int maximum (int x, int y)     /*determine the larger of two integer quantities*/

{
int z;
z= (x >= y)? x: y;
return(z);

}



main()
{
int a,b,c,d;

/*read the integer quantities*/


printf("\na=");
scanf("%d", &a);


printf("\nb=");
scanf("%d", &b); 

printf("\nc=");
 scanf("%d", &c);

/*calculate and display the maximum value*/

d=maximum(a,b);

printf("\n\maximum=%d", maximum(c,d));

}


The function maximum is accessed from two different places in main.In the first call to maximum the actual arguments are the variables a and b,whereas the arguments are c and d in the second call (d is a temporary variable representing the maximum value of  a and b ).
Note the two statements in main that access maximum i.e.

d=maximum(a,b);

printf("\n\maximum=%d", maximum(c,d)); 

These two statements can be replaced by a single statement

printf("\n\maximum=%d", maximum(c,maximum(a,b))); 


In this statement we see that one of the calls to maximum is an argument for the other call.Thus the calls are embedded,one within the other, and the intermediary variable, d,is not required.


No comments:

Post a Comment