Explain it simply
Explain it simply
A function is a named recipe. You write the steps once under a name such as showWelcome, and from then on a single line, showWelcome();, runs all of them. Some recipes need ingredients (parameters) and some hand back a finished dish (a return value).
Functions stop you from pasting the same lines into five places, and they let you read main() as a short list of steps instead of a wall of code.
Problem → Why → Solution
The problem: pasted copies of a rule drift apart
Without functions, a rule ends up pasted wherever it is needed. Below, a 10% discount appears three times. When the shop changed its discount, someone edited one copy and missed the others, so the third product is now priced by a different rule. Nothing crashes and there is no error: the program quietly gives inconsistent answers, the hardest kind of bug to notice.
#include <stdio.h>
int main(void) {
int price1 = 12000, price2 = 4500, price3 = 30000;
/* the same 10% discount rule, pasted three times */
int final1 = price1 - price1 * 10 / 100;
int final2 = price2 - price2 * 10 / 100;
int final3 = price3 - price3 * 15 / 100; /* only this copy was updated */
printf("%d %d %d\n", final1, final2, final3);
return 0;
}What does a function fix?
Every pasted copy is a separate place that has to be found and fixed. A function gives the rule one name and one body: int discounted(int price) { return price - price * 10 / 100; }. Change the body once and every caller gets the new rule, and reading the name tells you what each line of main does without decoding the arithmetic.
Core concept: define, call, return, copy
A function definition has four parts: the return type, the name, the parameter list in parentheses and the body in braces. int add(int a, int b) { return a + b; } promises an int result, is called add, takes two ints and computes their sum. A function that produces no value has the return type void, and a function that takes no arguments should say so with (void), as in void showWelcome(void).
Calling a function transfers control to its body. The argument values are copied into the parameters, the body runs, and return sends a value back to the exact spot of the call, where it can be stored, printed or passed on: int sum = add(5, 10);. return also ends the function immediately, so code after it does not run. Reaching the closing brace of a void function is an implicit return. In a non-void function every path must return a value: if the caller uses the result of a path that fell off the end, the behaviour is undefined, and gcc -Wall warns "control reaches end of non-void function". main is the one exception: reaching its closing brace returns 0.
C passes arguments by value. A parameter is a new local variable initialised with a copy of the argument, so assigning to it inside the function never changes the caller's variable. In the example, tryToChange sets its value to 100 while score in main stays 70. To let a function change the caller's data you pass an address instead, which the Pointers lesson covers; arrays already arrive as addresses, as the Arrays lesson showed.
The compiler reads a file from top to bottom, so it must know a function's signature before the first call. Either define the function above main, or put a prototype, the header followed by a semicolon, near the top: int add(int a, int b);. Since C99, calling an undeclared function is not allowed, and GCC reports "implicit declaration of function". Prototypes are also what header files contain, which the Function Declaration lesson explores further.
What happens during int sum = add(5, 10);
-----------------------------------------
main() add(int a, int b)
--------------------------- -----------------
int sum = add(5, 10); -- copies 5, 10 --> a = 5 b = 10
return a + b;
sum = 15 <---- returns 15 ----+
printf(...); main continues right after the call- Arguments are copied into parameters
- The body runs with those copies
- return hands one value back
- The caller resumes after the call
Whatever the body does to a parameter, it changes only the copy; the caller's variable is untouched.
General pattern
return_type function_name(type param1, type param2); /* prototype */
int main(void) {
variable = function_name(arg1, arg2); /* call */
}
return_type function_name(type param1, type param2) { /* definition */
statements;
return value; /* a void function has no value here */
}A prototype ends with a semicolon; the definition carries the body, and both must agree on the return type and parameter types. Write (void) for a function without parameters, and give a function that returns nothing the return type void.
Example: calling, returning and changing a copy
Three functions show three shapes: showWelcome takes nothing and returns nothing, add takes two ints and returns their sum, and tryToChange makes pass by value visible. All three live below main, so the file starts with their prototypes.
#include <stdio.h>
/* prototypes: each function's name, parameters and result */
void showWelcome(void);
int add(int a, int b);
void tryToChange(int value);
int main(void) {
showWelcome();
showWelcome();
int sum = add(5, 10);
printf("5 + 10 = %d\n", sum);
int score = 70;
tryToChange(score);
printf("score in main: %d\n", score);
return 0;
}
void showWelcome(void) {
printf("Welcome to C functions!\n");
}
int add(int a, int b) {
return a + b;
}
void tryToChange(int value) {
value = 100; /* changes the local copy only */
printf("value inside: %d\n", value);
}Code breakdown
- Prototype
int add(int a, int b);This line tells the compiler, before main calls add, what types the two arguments and the result have, so the call can be checked. Delete it and you get an implicit declaration error.
- Reuse
showWelcome();Each call runs the body from the top again, which is why the message appears twice. Changing the message means editing one line in the body.
- Using the return value
int sum = add(5, 10);5 and 10 are copied into a and b, return a + b; sends 15 back to this line, and it is stored in sum.
- Passing a copy
tryToChange(score);The value 70 is copied into the parameter value. Inside, value = 100; changes only that copy, so "value inside: 100" is printed while score in main is still 70.
- A function with no result
void showWelcome(void) {The first void says there is no result; the void in parentheses says there are no parameters, so a call such as showWelcome(42) is rejected by the compiler.
Welcome to C functions!
Welcome to C functions!
5 + 10 = 15
value inside: 100
score in main: 70return: leaving early and returning on every path
A function may contain several return statements; the first one reached ends the function. grade() checks the high scores first and returns at once, so it needs no chain of else branches, and the final return "C"; covers every remaining path. isEven() returns the result of a comparison, 1 or 0, directly.
#include <stdio.h>
int isEven(int n) {
return n % 2 == 0; /* return ends the function at once */
}
const char *grade(int score) {
if (score >= 80) {
return "A";
}
if (score >= 65) {
return "B";
}
return "C"; /* every path returns a value */
}
int main(void) {
printf("isEven(10) = %d, isEven(7) = %d\n", isEven(10), isEven(7));
printf("72 -> %s, 91 -> %s, 40 -> %s\n", grade(72), grade(91), grade(40));
return 0;
}The shape of a good function
A function should do one job, and its name should say what that job is: action names such as calculateTotal, printMenu or isValidAge make the calling line read like a sentence. Most functions fall into one of three kinds.
| Kind | Example name | Returns |
|---|---|---|
| Computes a value | calculateTotal | The computed value (int, double...) |
| Answers yes or no | isValidAge | 1 (true) or 0 (false) |
| Performs an action | printMenu | void (nothing) |
In real projects
Where this shows up in real projects
Real C programs are built almost entirely from functions. The standard library you have used since the first lesson (printf, strlen, snprintf) is itself a collection of them, and a project such as a web server or a database is thousands of small functions calling one another. Good codebases keep computation apart from input and output: a function like int parsePort(const char *text) that only converts and validates can be tested by calling it with a table of inputs and expected results, with no keyboard or file involved, while main() and a few thin functions handle the I/O.
Another convention you will meet constantly: many C APIs return a status (0 for success, nonzero or -1 for failure) and deliver the real result through a pointer parameter. If a number-parsing function returned -1 on error, the caller could not tell an error from a genuine -1, because one return value cannot be both data and an error flag when every int is valid data.
Common mistakes
Common mistakes
1. Calling a function defined below main without a prototype
Define average() below main without a prototype and GCC (version 14 and later) reports "implicit declaration of function 'average'" as an error. Older compilers only warned and guessed an int return type, which produced garbage for functions returning double. Put the prototype near the top of the file.
2. Writing () instead of (void)
In C17, void showWelcome() is a declaration that says nothing about parameters, so showWelcome(42) compiles without a single warning, even with -Wall -Wextra. C23 made () mean (void), and GCC 15 and later, which default to C23, reject the call with "too many arguments to function". Writing (void) gets you the check under every standard.
3. Forgetting return on one path
int square(int n) { n * n; } computes the value, throws it away and returns nothing, so using its result is undefined behaviour. Plain gcc says nothing, but -Wall warns "statement with no effect" and "control reaches end of non-void function". Write return n * n;.
4. Expecting a parameter change to reach the caller
void resetScore(int score) { score = 0; } never sets the caller's score to 0, because it changes a copy. Return the new value and assign it (score = resetScore(score);), or pass an address as shown in the Pointers lesson.
Best practices
Best practices
- Give each function one job and an action name.
- Write (void) for every function that takes no parameters.
- Keep a prototype at the top of the file for each function defined below main, matching its definition.
- Compile with -Wall so a missing return on any path is reported.
Mini challenge
Mini challenge: three helper functions
Define three functions below main, with prototypes at the top: maxOf returns the larger int, toFahrenheit converts Celsius to Fahrenheit, and printLine draws a line of dashes. Call them from main to print a small report.
- int maxOf(int a, int b) returns the larger value, including for negative numbers
- double toFahrenheit(double celsius) returns celsius * 9 / 5 + 32
- void printLine(int width) prints width dashes and a newline
- All three are defined below main, with prototypes at the top
#include <stdio.h>
// TODO: prototypes for maxOf, toFahrenheit and printLine
int main(void) {
// TODO: draw a line of 24 dashes
// TODO: print the larger of 12 and 30, then of -4 and -9
// TODO: print 35.0 and -40.0 Celsius in Fahrenheit with one decimal
// TODO: draw another line
return 0;
}
int maxOf(int a, int b) {
// TODO: return the larger value
}
double toFahrenheit(double celsius) {
// TODO: convert and return
}
void printLine(int width) {
// TODO: print width dashes, then a newline
}Expected: The program prints this report: ------------------------ Larger of 12 and 30: 30 Larger of -4 and -9: -4 35.0 C = 95.0 F -40.0 C = -40.0 F ------------------------
Show hint
Written with two ints, 9 / 5 is integer division and gives 1, so use double literals such as 9.0 / 5.0. For maxOf, one if and two return statements are enough.
Show solution
#include <stdio.h>
int maxOf(int a, int b);
double toFahrenheit(double celsius);
void printLine(int width);
int main(void) {
printLine(24);
printf("Larger of 12 and 30: %d\n", maxOf(12, 30));
printf("Larger of -4 and -9: %d\n", maxOf(-4, -9));
printf("35.0 C = %.1f F\n", toFahrenheit(35.0));
printf("-40.0 C = %.1f F\n", toFahrenheit(-40.0));
printLine(24);
return 0;
}
int maxOf(int a, int b) {
if (a > b) {
return a;
}
return b;
}
double toFahrenheit(double celsius) {
return celsius * 9.0 / 5.0 + 32.0;
}
void printLine(int width) {
for (int i = 0; i < width; i++) {
printf("-");
}
printf("\n");
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A function has a return type, a name, a parameter list and a body; void means no result (or, in the parentheses, no parameters).
- return sends one value back to the call site and ends the function; every path of a non-void function must return.
- C copies arguments into parameters, so changing a parameter never changes the caller's variable.
- Define or prototype a function before its first call, and write (void) when it takes no parameters.
GNU C compiler diagnostics — GNU Project