Calling Functions
To make a function run, you call it: you write its name, then parentheses and a semicolon. A function call is a statement. You call functions from the body of main:
#include <stdio.h>
void greet(void) {
printf("Hello!\n");
printf("Have a nice day!\n");
}
int main(void) {
greet();
return 0;
}This program prints:
Hello!
Have a nice day!When the program, while running main, reaches a function call, it jumps into the function and runs its body from top to bottom. Then it comes back and continues with the statement after the call. You can call a function as many times as you like:
#include <stdio.h>
void greet(void) {
printf("Hello!\n");
}
int main(void) {
printf("Start\n");
greet();
greet();
printf("End\n");
return 0;
}This program prints:
Start
Hello!
Hello!
EndThe program starts in main: it prints Start, runs the body of greet twice and finally prints End. A function that nobody calls never runs.
Calling a function is nothing new for you. printf is a function too, and every printf("Hello!\n"); you have written is a call: the name of the function, parentheses and a semicolon. So are strlen(name) and toupper(letter) from the lesson on strings. Somebody else wrote these functions for you. Later in this lesson, you will see how the compiler learns about them.
Watch out for two common mistakes:
- Missing parentheses.
greet;without parentheses doesn't call the function. The program compiles, but the function doesn't run and nothing is printed. - A different name. The name in the call must be exactly the same as in the definition, including upper and lower case. If you change the call in the first program to
Greet();, the program doesn't compile, and the error message starts like this:
main.c:9:5: error: call to undeclared function 'Greet'; ISO C99 and later do not support implicit function declarations [-Wimplicit-function-declaration]
9 | Greet();
| ^
main.c:9:5: note: did you mean 'greet'?“Call to undeclared function” means that the program calls a function that the compiler doesn't know. You will understand the rest of the first line in the next exercise. The line with note is a helpful hint: did you mean greet?
Instructions
In main, call the function print_banner in place of both comments. The program then prints the same as the long program in the previous exercise, but main is much shorter.
The game gets a third level. At the end of main, before return 0;, print Level 3 finished and call print_banner once more.
Add one more statement to the body of print_banner, between Well done! and the last line, that prints You earned a star. Run the program: the message has changed after all three levels. You changed the code in one place, and all three calls do something new. That's exactly what functions are good for.
Start programming for free
2/12