If I have an int main() method in C, and there is a returned value, does this value get saved in the stack after the return statement is executed or is there nothing visible in the stack after return?
-
It depends on the architecture and calling convention and return type. Typically on x86_64, for example, an integer return value will be stored in register rax, not on the stack. It will be different if you return a floating point value, or a struct, for example. – Crowman May 14 '17 at 16:19
-
C does not support _methods_. Nor does it mention using a stack! – too honest for this site May 14 '17 at 17:18
3 Answers
That is completely implementation dependent - the OS handles what happens before and after main
.
Chances are that there is a framework around the main call, which receives the return value and stores it in a local variable. But either way, you wouldn't be able to access it, as your program is over and done.

- 6,295
- 1
- 12
- 23
The C language does not define anything in regards to a stack, calling convention, or how an implementation satisfies the requirements of what happens when main
returns. In practice, on many implementations, the entry point code that invokes main
will do something like exit(main(argc, argv));
in which case the return value of main
certainly will be on the stack whenever calling convention puts the first argument to a function (exit
here) on the stack, but whether that's the case varies widely by implementation.

- 208,859
- 35
- 376
- 711
On the systems I know, main
is treated like any other function (and it has to be, for recursive calls to main to be possible), so the return value is passed in whatever way the ABI specifies for passing it. Usually that's not the stack, that would be slightly awkward since the stack frame of the function is destroyed when the function returns. On x86 systems return values are usually set in the EAX/RAX register.

- 6,221
- 16
- 30
-
'and it has to be, for recursive calls to main to be possible' - the standard/s mandate that recursive calls to main() must be allowed? – ThingyWotsit May 14 '17 at 19:26
-
@ThingyWotsit, C++ forbids it. C doesn't, but mentions that "a return from the _initial_ call to the main function is equivalent to calling the exit function" [\[1\]](http://stackoverflow.com/a/3728153/6372809) [\[2\]](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf) which implies that it's not forbidden. [random mention to the difference on SO](http://stackoverflow.com/questions/38560971/how-to-call-main-from-other-functions-in-c) – ilkkachu May 14 '17 at 20:09