Function Basics

When a program grows, the same few lines often appear in many places. A function helps here. It is a block of code with a name. You write the block once, and then you run it by its name whenever you need it.

You have already used one function in every program: main. Here is a program with a second function, printLine:

#include <iostream>
using namespace std;

void printLine() {
    cout << "----------" << "\n";
}

int main() {
    cout << "Order 1" << "\n";
    printLine();
    cout << "Order 2" << "\n";
    printLine();
    return 0;
}

Output:

Order 1
----------
Order 2
----------

The function has the same shape as main: a return type, a name, parentheses (), and a body in curly braces { }.

The return type of printLine is void. It means "this function gives nothing back". It only does a job, which here is printing a line. Functions that give a value back come in the Return Values lesson.

The line printLine(); inside main is a call. When the program reaches a call, it jumps into the function and runs its body. Then it comes back and continues with the line after the call. main calls printLine two times, so the line is printed two times.

Define it before you call it

The compiler reads your file from top to bottom. When it reaches a call, it must already know the function. That is why printLine is written above main. Here is the same program with the function moved below main:

#include <iostream>
using namespace std;

int main() {
    cout << "Order 1" << "\n";
    printLine();
    return 0;
}

void printLine() {
    cout << "----------" << "\n";
}

Output:

main.cpp: In function ‘int main()’:
main.cpp:6:5: error: ‘printLine’ was not declared in this scope; did you mean ‘inline’?

The compiler reached line 6, the call, before it had seen printLine. So it says the name "was not declared in this scope", which means it does not know that name at this point. (Ignore the guess inline at the end. The compiler suggests a word that looks similar, and here the guess is wrong.) Move the function back above main and the error goes away. The Function Declarations lesson shows a second way to fix it.

Why write functions?

If you want a different line tomorrow, say with = signs, you change one place, and every call prints the new line. A good name also makes main easier to read. printLine(); tells you what happens, while the cout line makes you read the code to find out. Large programs are built from many small functions like this one.

A call works anywhere a statement works, so you can also put one inside a loop. In the exercise, write a function named greet that prints a welcome line. main already calls it in a loop.