C Function Parameters
A parameter is a value a function receives when it is called. The call passes an argument, and the function can send an answer back as a return value.
One parameter, one answer
times_two sends back twice the number it receives. Main passes 5, so the print shows 10.
#include <stdio.h>
int times_two(int n) {
return n * 2;
}
int main() {
int answer = times_two(5);
printf("%d\n", answer);
return 0;
}Printing without an answer
print_age takes an age and prints it. Its type is void because it sends back no answer, so the print shows Age is 9.
#include <stdio.h>
void print_age(int age) {
printf("Age is %d\n", age);
}
int main() {
print_age(9);
return 0;
}Two parameters
add sends back the sum of the two numbers it receives. Main passes 3 and 4 in order, so the print shows 7.
#include <stdio.h>
int add(int a, int b) {
return a + b;
}
int main() {
int total = add(3, 4);
printf("%d\n", total);
return 0;
}Example
#include <stdio.h>
int square(int n) {
return n * n;
}
int main() {
printf("%d\n", square(4));
printf("%d\n", square(5));
return 0;
}Key points
- A parameter is named inside the brackets of a function.
- An argument is the value written in the call.
- Each argument fills one parameter, in order.
- A parameter works like a variable inside the function.
- The same function gives a new answer for each new argument.
- A return value is the answer a function sends back.
- The word return sends a value back to the call.
- The type in front of a function name is the type of its return value.
- int in front of a name means the return value is a whole number.
square takes a number and sends back the number times itself. Main calls square with 4 first, so 16 prints first. Then main calls square with 5, so 25 prints next.
Note
A parameter with no type does not compile.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which line passes 5 as an argument to times_two?