Prototyping in C++

Introduction: This tutorial is on how to use Function Prototyping in C/C++. Function File: Here is a basic function file which, after running the 'int main' function, runs a custom function named 'calculate' which returns an integer and is output to the screen.
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. int calculate(int num1, int num2) {
  6. return num1 + num2;
  7. }
  8.  
  9. int main()
  10. {
  11. cout << calculate(2, 4);
  12. return 0;
  13. }
The above code works perfectly fine, however if we were to re-arrange the function order to;
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. int main()
  6. {
  7. cout << calculate(2, 4);
  8. return 0;
  9. }
  10.  
  11. int calculate(int num1, int num2) {
  12. return num1 + num2;
  13. }
We get the following error;
  1. D:\Libaries\Documents\C Programs\Prototyping\main.cpp|8|error: 'calculate' was not declared in this scope|
Why The Error? We get the error because C++ works by running the code as it goes along, for each function it sees before it gets to the initial function ('main') it caches the delcaration line which includes the functions; Name Return Type Additional parameters including their reference names and data types. So in the first example, we have our 'calculate' function followed by our 'main' function. This means the once the 'main' function code is ran, the 'calculate' function code is already cached and therefore the C++ compiler hits no errors. In the second example, the 'main' function code tries to execute a 'calculate' function which the compilet has no recollection of ever seeing, and therefore throws an error which states the function does not exist. Work Arounds: There are two work arounds for this type of error/problem. The first is stated above simply consists of moving the main function above all others (and re-organising all custom functions in the correct order of calling so that no functions are called before they are declared). The second work around for this is to prototype a function. Prototyping a function is when the function return type, name, and parameters (again, including their reference names and data types) are cached at the top of the file, without declaring the function body. This allows the C++ compiler to know that there is going to be a function with the given return type, name, and parameters but just that the programmer has not yet specific the body - the part of the code which the function runs once it is called. We can prototype our above examples of 'main' and 'calculate' functions like so...
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. int calculate(int, int);
  6.  
  7. int main()
  8. {
  9. cout << calculate(2, 4);
  10. return 0;
  11. }
  12.  
  13. int calculate(int num1, int num2) {
  14. return num1 + num2;
  15. }
Finished!

Add new comment