5.1 Functions, Parameters, and Returns
A function is reusable code that performs a clear task. You have already used library functions such as printf() and scanf(). Now we define our own functions.
Defining functions
A C function states a return type, a name, a parameter list, and a body. The num1 and num2 in parentheses are parameters; the concrete values such as 4 and 12 passed at the call are arguments.
int larger(int num1, int num2) {
if (num1 > num2) {
return num1;
} else {
return num2;
}
}
int main(void) {
printf("%d\n", larger(4, 12));
printf("%d\n", larger(54, 33));
return 0;
}Output:
12
54return gives a result back to the caller and ends the current function call.
Functions without return values
Some functions perform an action without returning a useful result. Their return type is written as void.
void print_board(void) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
printf(" |");
}
printf("\n");
if (i < 2) {
printf("---+---+---\n");
}
}
}Output:
| |
---+---+---
| |
---+---+---
| |A void function has no meaningful return value. You can end it early with a bare return; or simply run to the end.
Function calls
When a function is called, the program temporarily leaves the current position and enters the function body. When the function finishes, execution returns to the original position. This "enter and return" process can be understood through the call stack.
The next program splits the "distance between two points" calculation into functions.
#include <stdio.h>
#include <math.h>
double square(double x) {
return x * x;
}
double distance(double x1, double y1, double x2, double y2) {
return sqrt(square(x1 - x2) + square(y1 - y2));
}
int main(void) {
printf("Distance: %.1f\n", distance(0, 0, 3, 4));
return 0;
}Output:
Distance: 5.0> Using sqrt() requires <math.h>, and on some systems you must also link with -lm.
Parameters and pass by value
Parameters make functions flexible: the same function receives different arguments and produces different results. C passes arguments by value, so the argument's value is copied into the parameter, and changing the parameter inside the function does not affect the caller's variable.
int square_value(int n) {
n = n * n; // changes only the copy
return n;
}
int main(void) {
int x = 5;
int y = square_value(x); // x is still 5, y is 25
printf("%d %d\n", x, y);
return 0;
}A function can take many parameters, but return can hand back only one value. Splitting work into small functions that return values keeps main short and makes each step easy to test on its own.
The main function
A C program always starts at main(), the entry point. The integer that main returns goes to the operating system, where 0 usually means a normal exit.
int main(void) {
printf("Program starts\n");
return 0;
}