Calling a function is done simply by specifying the name of the function followed by the parameters in parentheses:
x = max (4,3);
The parameters can be:
It is possible to mix the parameters as long as they respect the types declared in the prototype:
#define N 10
int max(int a, int b);
int main(void)
{
float x,y=2,z=18;
x = max (5,26); // Values
x = max(y,z); // Variables
x = max(y,N); // Variables and constant
x = max (max(y,z), 10); // Function and value
if (max(y,z) > 10) { // Variables in a test
...
}
...
}
The call to a function is always followed by parentheses to differentiate the function from variables with the same name. Let's analyze the following example:
int name (void) {
int name=26;
return name;
}
The above code implements a function name()
that contains a variable also called name
.
When name
is followed by parentheses, it is the function, otherwise the variable.
Without the parentheses, the compiler cannot differentiate the variable name
from the function name()
.
Parentheses are always added after the name of a function, even in text or comments.
Of course, this type of code should be avoided to prevent confusion.
Write a function average()
that returns the average of three floating-point numbers.
Test your function with a main program that asks the user to enter three values before displaying the average.
The average()
function should not display anything, but return the result of the calculation to the main program.
Enter the first value: 12.4 Enter the second value: 13.7 Enter the third value: 10.2 ----------------------- The average is 12.10
The call of the function ...
When calling a function, the parameters can be ...
Let's consider the following function, which calls are valid?
int max (int a, int b);
Let's consider a function max()
that returns the larger of two integers. What does the following code display?
int x;
x = max( 10, max (5,12));
printf ("%d", x );