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.
Function Definition
A function definition consists of four parts: return type, function name, parameter list, and function body.
int add(int a, int b) {
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:
int get_value(void) {
return 42;
}
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:
int x = add(add(1, 2), add(3, 4));
This is equivalent to add(3, 7), resulting in 10.
Parameters and Return Values
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).
int square(int n) {
return n * n;
}
int main(void) {
int x = 5;
int y = square(x);
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.
void try_change(int n) {
n = 100;
}
int main(void) {
int x = 5;
try_change(x);
printf("%d\n", x);
return 0;
}
The output is still 5, because n is only a copy of x.
Return Values
A function returns a result to the caller via the return statement. The return type must match the function declaration:
double circle_area(double r) {
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:
int max(int a, int b) {
if (a > b) {
return a;
}
return b;
}
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:
int add(int a, int b);
int main(void) {
int result = add(3, 5);
return 0;
}
int add(int a, int b) {
return a + b;
}
A declaration only includes the header followed by a semicolon; the function body is not needed. Parameter names can be omitted:
int add(int, int);
However, keeping parameter names improves readability and is recommended.
void Functions
Functions that do not need to return a value use void as the return type:
void print_line(int len) {
int i;
for (i = 0; i < len; i++) {
printf("-");
}
printf("\n");
}
In a void function, return can be omitted, or return; can be used to exit early:
void greet(int hour) {
if (hour < 0 || hour > 23) {
return;
}
if (hour < 12) {
printf("Good morning\n");
} else {
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:
#include <stdio.h>
int is_even(int n) {
return n % 2 == 0;
}
int main(void) {
int nums[] = {3, 4, 7, 8, 11, 16};
int i;
int len = sizeof(nums) / sizeof(nums[0]);
for (i = 0; i < len; i++) {
printf("%d is %s\n", nums[i], is_even(nums[i]) ? "even" : "odd");
}
return 0;
}
3 is odd
4 is even
7 is odd
8 is even
11 is odd
16 is even
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) {
if (score >= 90) return "Excellent";
if (score >= 80) return "Good";
if (score >= 60) return "Pass";
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.
Multi-Parameter Functions
A function can have multiple parameters, separated by commas. The number and types of arguments must match the parameters exactly:
double bmi(double weight, double height) {
return weight / (height * height);
}
Arguments are matched to parameters by position:
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):
#include <stdio.h>
int day_of_year(int year, int month, int day) {
int days_in_month[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int total = 0;
int m;
for (m = 1; m < month; m++) {
total += days_in_month[m];
}
total += day;
return total;
}
int days_between(int y1, int m1, int d1, int y2, int m2, int d2) {
int first = day_of_year(y1, m1, d1);
int second = day_of_year(y2, m2, d2);
int diff = second - first;
if (diff < 0) diff = -diff;
return diff;
}
int main(void) {
int d = days_between(2025, 3, 1, 2025, 6, 15);
printf("%d days apart\n", d);
return 0;
}
106 days apart
❓ 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.



