Give one job a clear function
Decompose a problem into named functions with explicit parameter and return-value contracts.
After this lesson
You should be able to
- Write and call a function whose declaration matches its definition.
- Decompose a calculation into cohesive, testable responsibilities.
A function is a promise
A declaration tells the compiler a function's name, parameter types, and return type. The definition supplies the body. A call must satisfy that contract. Write parameter names in declarations when they clarify meaning, even though only their types form the interface.
Use void in an empty parameter list to state that no arguments are accepted. A non-void function must return a value on every reachable path. Treat compiler warnings as defects, not decoration.
double rectangle_area(double width, double height);
int main(void) {
double area = rectangle_area(4.0, 2.5);
printf("%.2f\n", area);
return 0;
}
double rectangle_area(double width, double height) {
return width * height;
}Decompose around meaning
A useful function does one coherent job at one level of abstraction. calculate_average should calculate, while print_report should format output. Separating them lets the calculation be tested without inspecting terminal text.
Avoid functions that depend on unexplained global state. Prefer inputs through parameters and results through return values or explicit output parameters. The data flow then remains visible at the call site.
Try it yourself
Design a function that returns the larger of two integers.
Need a hint?
Its contract needs two int parameters and an int return type.
Check the worked solution
Keep comparison inside a small pure function.
int max_int(int a, int b) {
return a > b ? a : b;
}Quick check
What belongs in a function declaration?
Why this lesson exists
Syllabus mapping
Structured program design · Function declarations · Signatures · Parameters · Return types
Maps to course outcomes CO3, CO4.