It is also worth noting that in C++, int main() can be left without a return-statement, at which point it defaults to returning 0.
Short Answer: Nothing. Better Answer: return 0 it's used in main like a signal for know the exit of program was a success when return 0 executes. Best Answer: Still nothing because compilers already "put" return 0 in the the end of your code if you not explicit.
If you change to "void main()", you wouldn't need a return statement. You are passing return because there is not parameter passed into the "main"-function, so it's just an instruction to not give any value as output. Basically, returning "0" means that everything went fine.
That rule was added in the 1999 version of the C standard. In C90, the status returned is undefined.
You can enable it by passing -std=c99
to gcc.
As a side note, interestingly 9 is returned because it's the return of printf
which just wrote 9 characters.
It returns return value of printf
which is number of characters really printed out.
The return value from a function is normally stored in the eax register of the cpu, so the statement "return 4;" would usually compile to
mov eax, 4;
ret;
and return x (depending on your compiler) would be something like:
mov eax, [ebp + 4];
ret;
if you don't specify a return value then the compiler will still spit out the "ret" but doesn't change the value of eax. So the caller will think that what ever was left in the eax register previously is the return value. For this example it would usually be the return value printf, but different compilers will generate different machine code and use some registers differently.
This is a simplified explanation, different calling conventions and target platforms will play a vital role but it should be enough information to explain what is happening 'behind the scenes' in your example.
If you've got a basic understanding of assembler it's worth comparing the disassembly of different compilers. You may find that some compilers are clearing the eax register as a safeguard.
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