Step 3 of 7
void functions
Not every function computes a value. Some exist for what they do, like printing. Their return type is void, meaning "returns nothing":
#include <stdio.h>
void greet(int times) {
for (int i = 0; i < times; i++) {
printf("hi ");
}
printf("\n");
}
void banner(void) {
printf("=== START ===\n");
}
int main(void) {
banner();
greet(3);
greet(1);
return 0;
}
=== START ===
hi hi hi
hi
Details
- A
voidfunction doesn't need areturnstatement; it ends when it reaches the closing brace. You can still writereturn;(with no value) to leave early. - You can't use its result:
int x = banner();is a compile error, because there is no result. (void)in the parameter list means "takes no arguments". Call it with empty parentheses:banner(). Forgetting the parentheses (banner;) doesn't call it at all; the compiler warnsexpression result unused.
Why bother?
Even small helpers make code easier to read. print_bar(10) says what it does; a loop that prints ten = characters has to be read to be understood. And if you need the same output in five places, a function means one place to fix when it changes.
Your turn: write void print_bar(int n) that prints n = characters followed by a newline. print_bar(5) prints =====.