C: Function Basics
Functions are like recipes in a kitchen -- give them ingredients (parameters), they follow steps to process them, and serve a dish (return value). Encapsulating repeated logic into functions keeps code clean and efficient.
1. Function Definition
A function definition consists of four parts: return type, function name, parameter list, and function body.
// Function definition
int add(int a, int b) {
// Return result
return a + b;
}
int: the return type, indicating the type of the function's resultadd: the function name, used when calling(int a, int b): the parameter list, receiving data from the caller{ return a + b; }: the function body, executing the actual logic
If there are no parameters, write void in the parameter list:
// Function definition
int get_value(void) {
// Return result
return 42;
}
2. Function Calling
To call a function, follow the function name with parentheses and pass arguments:
int result = add(3, 5);
printf("%d\n", result);
When called, the program jumps to the function body, executes it, and returns to the call site upon encountering return or reaching the end of the function.
Functions can be nested -- the return value of one function can serve as the argument to another:
// Variable declaration
int x = add(add(1, 2), add(3, 4));
This is equivalent to add(3, 7), resulting in 10.
3. Parameters and Return Values
(1) Parameters vs Arguments
The variables in the parentheses of a function definition are called parameters (formal parameters). The values passed when calling are called arguments (actual parameters).
// Function definition
int square(int n) {
// Return result
return n * n;
}
// Function definition
int main(void) {
// Variable declaration
int x = 5;
// Variable declaration
int y = square(x);
// Return result
return 0;
}
n is a parameter, x is an argument. Parameters are local variables within the function; the argument's value is copied to the parameter -- this is "pass by value". Modifying the parameter inside the function does not affect the argument.
// Function definition
void try_change(int n) {
n = 100;
}
// Function definition
int main(void) {
// Variable declaration
int x = 5;
try_change(x);
// I/O operation
printf("%d\n", x);
// Return result
return 0;
}
The output is still 5, because n is only a copy of x.
(2) Return Values
A function returns a result to the caller via the return statement. The return type must match the function declaration:
// Function definition
double circle_area(double r) {
// Return result
return 3.14159 * r * r;
}
A function can return an expression directly without storing it in a variable first. Once return executes, the function ends immediately; subsequent code is not executed:
// Function definition
int max(int a, int b) {
// Conditional check
if (a > b) {
// Return result
return a;
}
// Return result
return b;
}
4. Function Declaration (Prototype)
If a function is defined after the point where it is called, the compiler does not recognize the function name and will produce an error or implicitly assume it returns int. The solution is to declare the function prototype before the call:
// Function definition
int add(int a, int b);
// Function definition
int main(void) {
// Variable declaration
int result = add(3, 5);
// Return result
return 0;
}
// Function definition
int add(int a, int b) {
// Return result
return a + b;
}
A declaration only includes the header followed by a semicolon; the function body is not needed. Parameter names can be omitted:
// Function definition
int add(int, int);
However, keeping parameter names improves readability and is recommended.
5. void Functions
Functions that do not need to return a value use void as the return type:
// Function definition
void print_line(int len) {
// Variable declaration
int i;
// For loop
for (i = 0; i < len; i++) {
// I/O operation
printf("-");
}
// I/O operation
printf("\n");
}
In a void function, return can be omitted, or return; can be used to exit early:
// Function definition
void greet(int hour) {
// Conditional check
if (hour < 0 || hour > 23) {
// Return result
return;
}
// Conditional check
if (hour < 12) {
// I/O operation
printf("Good morning\n");
} else {
// I/O operation
printf("Good afternoon\n");
}
}
void function cannot return a value; return 5; will cause a compile error. Similarly, every execution path in a non-void function must have a return with the correct type.
▶ Example
Determine whether an integer is even:
▶ Try it Yourself3 is odd
4 is even
7 is odd
8 is even
11 is odd
16 is even
6. The return Statement in Detail
A function can have multiple return statements, but only one executes per call. return has two effects:
- Return a value to the caller
- Immediately terminate function execution
const char *grade(int score) {
// Conditional check
if (score >= 90) return "Excellent";
// Conditional check
if (score >= 80) return "Good";
// Conditional check
if (score >= 60) return "Pass";
// Return result
return "Fail";
}
The return value is copied to the call site. For basic types (int, double, etc.), the copy overhead is negligible. After a function returns, its local variables no longer exist, so you must not return a pointer to a local variable.
7. Multi-Parameter Functions
A function can have multiple parameters, separated by commas. The number and types of arguments must match the parameters exactly:
// Function definition
double bmi(double weight, double height) {
// Return result
return weight / (height * height);
}
Arguments are matched to parameters by position:
// Variable declaration
double result = bmi(70.0, 1.75);
▶ Example
Calculate the number of days between two dates (simplified version, ignoring leap years and month differences, just demonstrating multi-parameter functions):
▶ Try it Yourself106 days apart
▶ Example 3: Sum Array via Function
▶ Try it Yourself输出:
TEXTSum = 150
❓ FAQ
return; in a void function?break in a loop.📖 Summary
- A function consists of a return type, function name, parameter list, and function body
- Arguments are copied to parameters (pass by value); modifying parameters inside the function does not affect arguments
- A function must be declared or defined before it is called; a prototype declaration is sufficient
- void functions do not return a value; use
return;to exit early - The return statement immediately terminates the function and sends a value back to the caller
📝 Exercises
- Write a function
int max3(int a, int b, int c)that returns the largest of three integers. - Write a function
void swap_wrong(int a, int b)that attempts to swap two values. Verify in main whether it succeeds, and explain why. - Write a function
int digit_sum(int n)that calculates the sum of the digits of a positive integer (e.g., 123 returns 6). Test it in main.