Re:C++ main function doesn't need return but has int return ...
by argorain on Wednesday January 29, 2025 @03:34AM
(#42862824)
TIL C++ has exception for main function to be without return even though they forced it to have int return type. Can someone explain to me why this was done? C was happy with void return type but C++ forces int, yet implicitly adds return 0 if missing.
[ Parent
| on HN ]
Re:C++ main function doesn't need return but has int return ...
by DamonHD on Wednesday January 29, 2025 @03:51AM
(#42862916)
So as to avoid accidentally returning a random (bad) status code for the whole process in the case where no explicitly return is coded. Equivalent to allowing a void return type in C I guess, but maybe less smelly given that the process does actually return something, typically, eg in POSIX environments.
Re:C++ main function doesn't need return but has int return ...
by 2c2c2c on Wednesday January 29, 2025 @03:52AM
(#42862925)
no idea why it was done, but iirc people still wrote it until gurus started emphasizing that you shouldn't around c++11. around that time there was a strong push to differentiate code from looking like "C with classes"
Re:C++ main function doesn't need return but has int return ...
by eesmith on Wednesday January 29, 2025 @05:27AM
(#42863454)
I'm pretty sure main is supposed to be declared with an int return type, but the compiler may specify something else.
My reading of https://www.open-std.org/jtc1/sc22/WG14/www/docs/n1256.pdf says the C99 spec requires "int main(void)", "int main(int argc, char *argv[])" or "some other implementation-defined manner".
There's also the clause that if the type is compatible with int then "reaching the } that terminates the main function returns a value of 0.".
In other words, C implicitly adds return 0 if missing (and appropriate).