Parameters
- C course
- Beginner
- Lesson 67/116
- 4 min
Learn to pass parameters to a function and call by value.
Taking data with parameters
Parameters specify the data a function takes from outside. Each parameter has a type and a name.
void greet(char name[]) {
printf("Hello, %s!\n", name);
}
int main(void) {
greet("Anna"); /* Hello, Anna! */
}When calling, you put a value (argument) inside the parentheses. Parameter and argument are different: the parameter is in the definition, the argument is in the call.
Multiple parameters
Multiple parameters are separated by commas. Each parameter needs its own type.
int divide(int dividend, int divisor) {
return dividend / divisor;
}
int seven = divide(14, 2); /* seven = 7 */Order matters: the first argument goes to the first parameter, the second to the second. divide(2, 14) gives a different result (0).
Practice Sum of three numbers
Define int add(int a, int b, int c) with body return a + b + c;. Call printf("%d\n", add(2, 3, 4)); from main. Output should be 9.
Starter code
#include <stdio.h>
/* define add function */
int main(void) {
/* call printf %d with add(2, 3, 4) */
return 0;
}Sample solution
#include <stdio.h>
int add(int a, int b, int c) {
return a + b + c;
}
int main(void) {
printf("%d\n", add(2, 3, 4));
return 0;
}Expected output
9
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match parameter concepts
| Term | Meaning |
|---|---|
parameter |
in definition |
argument |
in call |
type |
int, char, double |
name |
identifier |
2 Two-parameter definition
int add(int a, ____) {
return a + b;
}
int add(int a, int b) {
return a + b;
}
Explanation: Each parameter has its type.
3 What is written for each parameter in a parameter list?
- Value
- Only name
- Only type
- Type and name Correct answer
Explanation: Each parameter has a type and a name together.