Are there some special rules with respect to the declaration of the main
function?
According to ideone this is legal C++:
main() // As opposed to int main()
{
return 0;
}
On the other hand, normal functions do not seem to have the privilege to avoid the return type:
f(){}
int main()
{
return 0;
}
Gives the error:
prog.cpp:1:3: error: ISO C++ forbids declaration of 'f' with no type [-fpermissive] f(){} ^
Is the main
function special in this case?
Master C and Embedded C Programming- Learn as you go In C++ language, the main() function can be left without return value. By default, it will return zero.
In a main function, the return statement and expression are optional.
C++ does not allow main to have a void return type. The published C++ standard requires it to be int . Some C++ compilers allow you to use void , but that's not recommended.
Yes. According to C standard, main() should return a int value.
Never omit main
's return type, as it's non-standard!
wandbox example:
prog.cc:1:6: warning: ISO C++ forbids declaration of 'main' with no type [-Wpedantic] main()
From $3.6.1:
1 A program shall contain a global function called main, which is the designated start of the program. It is implementation-defined whether a program in a freestanding environment is required to define a main function. [ Note: In a freestanding environment, start-up and termination is implementation-defined; startup contains the execution of constructors for objects of namespace scope with static storage duration; termination contains the execution of destructors for objects with static storage duration. — end note ] § 3.6.1 58
2 An implementation shall not predefine the main function. This function shall not be overloaded. It shall have a return type of type int, but otherwise its type is implementation-defined
No, it works because compilers support really old C, that allowed that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With