C++ functions: Function Prototypes

A function prototype declares a function without having to implement it.

Before a function is called, its header must be declared. One way to ensure this is to place the definition before all function calls. Another approach is to define a function prototype before the function is called. A function prototype, also known as function declaration, is a function header without implementation. The implementation is given later in the program.

Listing 6.7 rewrites Listing 6.6, TestFunctionOverloading.cpp, using function prototypes. Three max function prototypes are defined in lines 5-7. These functions are called later in the main function. The functions are implemented in lines 27, 36, and 45.

Listing 6.7 TestFunctionPrototype.cpp

1 #include <iostream>
2
using namespace std;
3

4 // Function prototype

5 int max(int num1, int num2);
6 double max(double num1, double num2);
7 double max(double num1, double num2, double num3);

8

9 int main()

10 {
11   
// Invoke the max function with int parameters
12    cout << “The maximum between 3 and 4 is ” <<

13    max(3, 4) << endl;

14

15    // Invoke the max function with the double parameters

16    cout << “The maximum between 3.0 and 5.4 is ”

17    << max(3.0, 5.4) << endl;

18

19    // Invoke the max function with three double parameters

20    cout << “The maximum between 3.0, 5.4, and 10.14 is ”

21    << max(3.0, 5.4, 10.14) << endl;

22

23    return 0;

24 }
25

26 // Return the max between two int values

27 int max(int num1, int num2)

28 {
29   
if (num1 > num2)
30       
return num1;
31   
else
32       return num2;
33 }
34

35    // Find the max between two double values

36    double max(double num1, double num2)

37 {
38     
if (num1 > num2)
39       
return num1;
40   
else
41       return num2;
42 }
43

44    // Return the max among three double values

45    double max(double num1, double num2, double num3)

46 {
47     
return max(max(num1, num2), num3);
48 }

Source: Liang Y. Daniel (2013), Introduction to programming with C++, Pearson; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *