Why main does not return 0 here? Why main does not return 0 here? c c

Why main does not return 0 here?


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.