I was taught that functions need declarations to be called. To illustrate, the following example would give me an error as there is no declaration for the function sum
:
#include <iostream>
int main() {
std::cout << "The result is " << sum(1, 2);
return 0;
}
int sum(int x, int y) {
return x + y;
}
// main.cpp:4:36: error: use of undeclared identifier 'sum'
// std::cout << "The result is " << sum(1, 2);
// ^
// 1 error generated.
To fix this, I'd add the declaration:
#include <iostream>
int sum(int x, int y); // declaration
int main() {
std::cout << "The result is " << sum(1, 2);
return 0;
}
int sum(int x, int y) {
return x + y;
}
Why the main
function doesn't need the declaration, as other functions like sum
need?
main
. In C++ you aren't; it isn't "just a function" -- it's special. Historically, the reason is that compilers added code tomain
to initialize global variables that required dynamic initialization; callingmain
from inside the program would re-initialize those variables, and the result would be chaos.sum
if you put the definition above main in the file. For this reason, it is common to seemain
as the last function in C and C++ source code, so you don't need to have forward declarations for other functions defined in that file. Not like C# and Java that often putmain
first, although it is not required in those cases.main
, a definition of a function also declares the function. That's why you can movesum
beforemain
to avoid having to separately declaresum
.