3.6. Definitions and Uses¶
Pulling together all the code fragments from the previous section, the whole program looks like this:
1#include <iostream>
2
3void new_line () {
4 std::cout << '\n';
5}
6
7void three_line () {
8 new_line (); new_line (); new_line ();
9}
10
11int main () {
12 std::cout << "First Line.\n";
13 three_line ();
14 std::cout << "Second Line.\n";
15 return 0;
16}
This program contains three function definitions: new_line, three_line,
and main.
Inside the definition of main, there is a statement that uses or calls
three_line. Similarly, three_line calls new_line three times. Notice that
the definition of each function appears above the place where it is
used.
This is necessary in C++; the declaration or definition of a function must appear before (above) the first use of the function. It is possible for only the declarations for appear before a function is used and for the definition to appear later. These are called forward declarations.
1#include <iostream>
2
3// forward declarations
4void new_line ();
5void three_line ();
6
7int main () {
8 std::cout << "First Line.\n";
9 three_line ();
10 std::cout << "Second Line.\n";
11 return 0;
12}
13
14void new_line () {
15 std::cout << '\n';
16}
17
18void three_line () {
19 new_line (); new_line (); new_line ();
20}
Try This!
You should try compiling both programs with the functions in a different order and see what error messages you get.
Q1
The function declaration or definition must be written the first use of the function.
Q2
Which of the following is a correct function header (first line of a function definition)?
Q3
Construct a block of code that correctly defines the add_two function.
-
add_two(int x) #distractor -
int add_two(int x) #distractor -
int add_two(int x) { -
int add_two(int x); #distractor -
int result = x + 2; -
return result; -
return x; #distractor -
}
More to Explore
From cppreference.com