Question about int main() and return 0 commands

May 6, 2020 at 7:42pm
Hello. I am new to the C++ language. I Googled my question, but I didn't understand the answers.

My question is when we write int main() the int there stands for integer and the return 0 command sends an integer (0) to the computer? Does int and return work this way? Also, I tried the code without putting int before main() but it still worked. Why is that.

Sorry if this question is so easy. I am new to programming.


May 6, 2020 at 7:47pm
The "int" in the main() function designates the return type of main. If you have already learned about functions, you would know that all functions have a return type (which can be "void" if the function does not return anything). In modern C++, the main() function returns an integer. When you "return" from main, the program ends. Historically, returning "0" means that the program returned successfully. Programmers could use "return 1" to indicate some abnormal termination, if desired.
May 6, 2020 at 7:56pm
In C++ the function main() must be declared to return an int, int main(). The int means that you promise to return an int from this function, but because main() is special if you fail to actually return something the compiler will automatically return zero for you.

Also, I tried the code without putting int before main() but it still worked. Why is that.

If you have a properly configured compiler not have int before main() should result in an error from the compiler. If your compiler is not warning you about this issue it is either broken, or not a strictly conforming compiler.

And note several Windows compilers used to allow this behavior as a "feature" to prevent breaking old code, I'm not sure if this is still the case since I don't do Windows.
Last edited on May 6, 2020 at 7:58pm
May 6, 2020 at 8:10pm
Historically, returning "0" means that the program returned successfully.
And currently! This is still a quick, easy way to express/determine failure in scripts and such (as long as you know the documentation of the program you're calling).
Last edited on May 6, 2020 at 8:11pm
May 6, 2020 at 8:42pm
return 0 is actually for the OS. All modern and most historic OS understand 0 is ok and others are an error. It prints the error on the console. Lets say you get a problem and do return 1, then you provide your users with a manual or -h help command or something that says 'if you get a return code of 1, your network is unplugged' or whatever.

Long ago I had a double main() progarm that computed a value from command line args and trapped the answer back. I don't think modern compilers tolerate this hackery :) It would still work for integer types, but its unclean. It was unclean then too, but it was the fastest way to do what needed doing and systems were very slow.
Last edited on May 6, 2020 at 8:43pm
Topic archived. No new replies allowed.