Learn C · lesson 21 of 60 · about 7 minutes
Defining Functions
Start the report's summary between two dividers: package a line of code into your own function and call it from main.
What you'll learn
- Define a void function
- Call a function
- Explain why functions help
A divider for the summary
The report is getting long, so it should end with a summary that's easy to spot, with a divider line above and below the word Summary. The same printf twice would work, but if the divider ever changes it has to be changed twice. A function gives that line a name, print_divider, and every call prints it.
Name a piece of code
You've been writing one function all along: main. You can write your own too.
void cheer(void) { ... } defines a function called cheer. void at the front means it doesn't give back a value; (void) means it takes no inputs. Writing cheer(); calls it, running its body.
Define once, call twice
#include <stdio.h>
void cheer(void) {
printf("Go Phoebe!\n");
}
int main(void) {
cheer();
printf("...\n");
cheer();
return 0;
}Output
Go Phoebe!
...
Go Phoebe!Why bother?
- Reuse: write it once, call it many times
- Names:
print_menu()explains itself - Fix once: a bug fixed in the function is fixed everywhere it's used
Tip
In C, a function must be defined (or declared) above the code that calls it. You'll see how to get around that with prototypes later in this unit.
Now try it yourself
This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.