0

What is the best use of function proto-typing in c++?

For instance I understand you can use it to place functions below the scope of your 'main' function. When is this considered useful?

I always like to have my main at the bottom of the main file as a personal preference.

I do not have a whole lot of experience with C++ and trying to get better with it.

I did notice that it seems to have a quicker execution time if you do not proto type.

Staver
  • 63
  • 8
  • 1
    Perhaps you will be interested in this: http://stackoverflow.com/questions/4757565/what-are-forward-declarations-in-c – nakiya May 05 '17 at 05:17
  • Usually "best practices" questions tend to have opinionated answers - voting to close. – Patrick Roberts May 05 '17 at 05:19
  • Patrick, I really just want to understand this concept and when it is useful and when it should be avoided. I understand much of programming is opinionated. – Staver May 05 '17 at 05:20
  • I have found that this is a consideration when you have a small, non-production piece of code. If the code is anything beyond trivial, there are multiple files and the prototypes exist in header files. I don't see how the presence of prototypes can slow down code? Do you mean runtime execution time or compilation time? – Paul Rooney May 05 '17 at 05:25
  • And I like my main function at the top of the source file, because that is where the work starts, and all functions underneath. Then, of course, you need the prototypes. So, yes, this is very opinion based. But, I don't see a way how using prototypes could have a performance impact. – Rene May 05 '17 at 05:30
  • It is unavoidable if you have multiple source files – M.M May 05 '17 at 05:50

1 Answers1

2

By far the most useful effect of having function prototypes is that you don't need to put all your function definitions in their respective headers. If this was the case, compile time would go through the roof!

Another important case where it's necessary is when two function implementations have a cyclical dependency on one another. Putting these cyclical dependent definitions after both functions have been declared makes this possible. This is sometimes necessary even for function templates.

rubenvb
  • 74,642
  • 33
  • 187
  • 332