Function Declarations

In the Function Basics lesson, you called printLine from main when printLine was written below main. The compiler stopped with "was not declared in this scope", because it reads the file from top to bottom. The fix was to move the function above main.

There is a second way to fix it. You can tell the compiler about a function first, and write its body later. A declaration (also called a prototype) is the first line of the function, with a ; at the end instead of a body. It says that the function exists, and what it takes and gives back. The definition is the full function with its body, the kind you have written so far.

#include <iostream>
using namespace std;

int square(int n);

int main() {
    cout << square(4) << "\n";
    cout << square(9) << "\n";
    return 0;
}

int square(int n) {
    return n * n;
}

Output:

16
81

Line 4 is the declaration. When the compiler reaches square(4) in main, it already knows that square takes an int and gives back an int. That is all it needs to check the call. The body comes at the bottom of the file.

Why use declarations?

With declarations at the top, main can come first. A reader opens the file and sees what the program does before the details. When there are many functions, you also do not have to put them in a careful order, because every function can call every other one. Large programs go one step further: they keep the declarations in separate files, called header files, and bring them in with #include.

In a declaration, the parameter names are optional. int square(int); also works. But a name like n, or price, tells the reader what the value is, so most programmers keep them.

Do not forget the semicolon

A declaration must end with ;. Without it, the compiler thinks the function body is still coming:

#include <iostream>
using namespace std;

int square(int n)

int main() {
    cout << square(4) << "\n";
    return 0;
}

int square(int n) {
    return n * n;
}

Output:

main.cpp:6:1: error: expected initializer before ‘int’

The mistake is on line 4, but the error points at line 6, where the compiler found int main instead of a body. Error messages often point at the line after the real mistake, so look at the line above too.

The declaration must match the definition

The return type, the name and the parameter types must be the same in both places. If the declaration says int square(int n); but the definition says int square(double n), C++ treats them as two different functions. The one that main calls never gets a body, and the build stops with a message like undefined reference to `square(int)'. You get the same message if you write a declaration and forget the definition.

In the exercise, main calls two functions that are defined below it. Write their declarations above main.