Deep dive into C functions: pass-by-value, call stack, recursion.
Functions with return values
A function takes parameters, performs a computation, and can return a value.
intsquare(int n) { // return type: intreturn n * n; // return a value
}
intmain(void) {
int r = square(5); // call the function; r becomes 25printf("%d\n", r);
}
Argument
Value passed to the function. Goes in the parentheses.
Return value
Result the function returns, via the return statement.
name(args)
Call expression. Its value is the return value.
void — "nothing"
Use void to indicate "no parameters" or "no return value".
// no return, no parametersvoidsayHello(void) {
printf("Hello!\n"); // return can be omitted
}
// no return, with parametervoidprintBox(int n) {
for(int i=0; i<n; i++) printf("*");
printf("\n");
}
// returns a value, no parametersintgetAnswer(void) {
return42;
}
main function:int main(void) means "no parameters, returns int".
Multiple parameters & types
You can pass multiple parameters separated by commas. Each one needs its type.