C/C++ Arena

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

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 =====.

Previous: Write a function Next: Prototypes