Search code examples
c++functionfunction-prototypes

Prototyping a function - C++


Lately, some of my CPP tutorials have used function prototypes . I understand you must initialize the function, but what is the overall use of it? Couldn't you use just as well write the entire function before main() instead of defining a prototype?

int returnValue(void);

int main()
{
  std::cout << returnValue() << std::endl;
  return 0;
}

int returnValue(void)
{
  return 10;
}

Solution

  • One important usage case is when you separate your implementation from the declarations. In other words, you declare your functions/classes etc in a header file, and define (i.e. implement) them in cpp files. In this way, you can distribute your program with the implementation fully compiled in a shared or static library. In order to use a pre-compiled function you need to introduce it to your program via a declaration. Example:

    a.h

    void f();
    

    a.cpp

    void f(){/* implementation here */}
    

    main.cpp

    #include "a.h"
    
    int main()
    {
        f();
    }
    

    Including "a.h" in main() is declaring the function. Once you compile the a.cpp once, you don't need it's source any more, the program will run provided you have at least access to the object file, but in order for the linker to find the function f() you need to declare it.