C Functions
A function is a named piece of code that runs when its name is called. Writing it once keeps main short, because the same job never needs writing twice.
Define and call a function
greet is defined once and called once. The call runs the print line inside greet, so Hello! appears once.
#include <stdio.h>
void greet(void) {
printf("Hello!\n");
}
int main() {
greet();
return 0;
}Call the same function twice
say_hi is called twice. Each call prints the line again, so the output holds two copies.
#include <stdio.h>
void say_hi(void) {
printf("Hi there!\n");
}
int main() {
say_hi();
say_hi();
return 0;
}Two functions in one program
Two functions are defined here. Main calls first, then second, so the output follows that order.
#include <stdio.h>
void first(void) {
printf("First.\n");
}
void second(void) {
printf("Second.\n");
}
int main() {
first();
second();
return 0;
}Example
#include <stdio.h>
void greet(void) {
printf("Good morning.\n");
}
void farewell(void) {
printf("Goodbye.\n");
}
int main() {
greet();
printf("Have a nice day.\n");
farewell();
return 0;
}Key points
- A function has a name and a block of code.
- You define a function by writing its name and its block.
- You call a function by writing its name and a pair of round brackets.
- Calling a function runs the code inside it.
- The same function can be called more than once.
- A function keeps one job in one place, so main stays short.
- The word void inside the brackets means the function needs nothing to run.
- Write a function above main, so main can call it.
main calls greet first, so Good morning prints first. Then main prints a line of its own. Then main calls farewell, so Goodbye prints last.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which line calls a function named greet?