RETURNING FUNCTION RESULTS
This is done by the use of the keyword return, followed by
a data variable or constant value, the data type of which must
match that of the declared return_data_type for the function.
float add_numbers( float n1, float n2 ) { return n1 + n2; /* legal */ return 6; /* illegal, not the same data type */ return 6.0; /* legal */ }
It is possible for a function to have multiple return statements.
int validate_input( char command ) { switch( command ) { case '+' : case '-' : return 1; case '*' : case '/' : return 2; default : return 0; } }
Here is another example
/* Simple multiply program using argument passing */ #include <stdio.h> int calc_result( int, int ); /* ANSI function prototype */ int calc_result( int numb1, int numb2 ) { auto int result; result = numb1 * numb2; return result; } main() { int digit1 = 10, digit2 = 30, answer = 0; answer = calc_result( digit1, digit2 ); printf("%d multiplied by %d is %d\n", digit1, digit2, answer ); } Sample Program Output 10 multiplied by 30 is 300
NOTE that the value which is returned from the function (ie result) must be declared in the function.
NOTE: The formal declaration of the function name is preceded by the data type which is returned,
int calc_result ( numb1, numb2 )
EXERCISE C15
Write a program in C which incorporates a function using
parameter passing and performs the addition of three numbers. The
main section of the program is to print the result.