3.6. Definitions and Uses

Pulling together all the code fragments from the previous section, the whole program looks like this:

Using function definitions
 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.

Using function definitions
 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.

  1. add_two(int x) #distractor
  2. int add_two(int x) #distractor
  3. int add_two(int x) {
  4. int add_two(int x); #distractor
  5. int result = x + 2;
  6. return result;
  7. return x; #distractor
  8. }


More to Explore