-1

Why declare a function before defining it? I'm using C++. I know someone may thing this is a childish question, but I'm really confused.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • *I'm using c++ language* Then why did you tag your question with Java and C? – Elliott Frisch Feb 24 '20 at 03:45
  • Because when you're writing a library containing several thousands functions and class methods, in a million lines of code, trying to sort all of these functions in order, so that every function is always defined before it's used, would be a slightly complicated task. – Sam Varshavchik Feb 24 '20 at 03:47
  • 2
    Does this answer your question? [Why are forward declarations necessary?](https://stackoverflow.com/questions/2632601/why-are-forward-declarations-necessary) – Brian61354270 Feb 24 '20 at 03:47
  • In C/C++ you can just define a function, and use it *later* (the definition serves as declaration too). But that cramps order of writing your code. Declare, use at will, define wherever you want. – vonbrand Feb 24 '20 at 12:30

1 Answers1

1

Why declare a function before defining it?

Because it's likely that some or all of the code that wants to call your function will not have access to the definition. Consider a function that is defined in a different .cpp file than your function; when compiling that .cpp, the compiler is not going to load in your function's .cpp file to check the function's name, argument types, and return type -- but we still want the compiler to emit an error when the function is called incorrectly, so the compiler needs to know about your function's name and signature somehow -- and the solution the C++ designers went with is to put a declaration of the function's name and signature in a separate .h file that the compiler does have access to (via #include).

(And if you're wondering why the compiler can't just read in all the necessary .cpp files instead -- it theoretically could, albeit at the cost of increasing compile time -- but that would still leave us with a problem in the use-case where the .cpp file containing your function doesn't exist on the system that wants to use your function, because your function has been provided to the calling code only as part of a pre-compiled library. In that case, the separate declaration inside a .h file is still necessary)

Jeremy Friesner
  • 70,199
  • 15
  • 131
  • 234