Defining and Calling Functions
beginner11 min readLesson 22 of 148
The anatomy of a function: return type, name, parameters, body, and the call.
Anatomy
int add(int a, int b) { // return type, name, parameters
return a + b; // body: compute and return
}
int sum = add(2, 3); // call: arguments 2 and 3
A function packages a computation under a name. Define it once, call it many
times. void means "returns nothing":
void greet(const char* name) {
printf("Hello, %s!\n", name);
return; // optional for void
}
Why functions
- Name the idea โ
is_leap(y)reads better than a wall of conditions. - Test in isolation โ a pure function is trivially testable (our whole grading model depends on this).
- One responsibility โ if you can't name it in a few words, split it.
Execution
A call jumps to the body, runs it, and resumes right after the call site, carrying the return value. Arguments are copies (module 11 shows how to let a function modify the caller's variables).