Functions
Write code once, use it many times.
4 minute read
Big idea
A function is a named piece of code. Write it once, then call it by name as often as you like.
The idea
You've used functions from day one — printf and scanf are functions someone else wrote. main is one too: it's where every C program starts. Now you'll write your own.
void greet(void) {
printf("Hello!\n");
}
void(first) — this function doesn't give back a value.greet— its name.(void)— it takes no inputs.{ … }— the body: what runs each time it's called.
Calling it runs the body: greet();
#include <stdio.h>
void greet(void) {
printf("Hello!\n");
}
int main(void) {
greet();
greet();
greet();
return 0;
}output
Hello!
Hello!
Hello!Run and edit it in the app.
Why bother?
- No copy-paste. Fix a bug in one place and every call gets the fix.
- Names explain.
print_receipt();says what's happening; twenty lines ofprintfdon't. - Small pieces. A long program becomes a set of short functions you can understand one at a time.
Define before you call
C reads your file from top to bottom. If main calls greet before C has seen it, you get a warning or an error. Either put the function above main, or put a prototype — the first line with a ; — at the top:
#include <stdio.h>
void greet(void); // prototype: "greet exists, the body comes later"
int main(void) {
greet();
return 0;
}
void greet(void) {
printf("Hello!\n");
}
#include <stdio.h>
void middle(void) {
printf("2\n");
}
int main(void) {
printf("1\n");
middle();
printf("3\n");
return 0;
}What does it print? Show the answer
1
2
3Run and edit it in the app.
A call jumps into the function, runs it to the end, then comes back to exactly where it left off.
Watch it
Think of it like
A recipe card named "Pancakes". Instead of rewriting the steps every Sunday, you say "make Pancakes" and follow the card.
🕷️ Spidey-sense:
thwip();— I didn't re-engineer my web-shooters every time I fire them. Built once, called a thousand times a night.
Key terms
- Function — A named, reusable block of code.
- Call — Running a function by writing its name with brackets:
greet(); - Definition — The function's header plus its body.
- Prototype — Just the header with a
;, telling C the function exists.
Check yourself
What does void mean as a function's return type?
What is a prototype?
After a function finishes, execution continues…