How do C++ progs get their return value, when a return is not specified in the function?

On x86 calling conventions, the return value for integers and pointers is on the EAX register. The following is an example of that:

int func() {
    if(0) return 5; // otherwise error C4716: 'func' : must return a value
int main() {
    int a;
    a = func();

Compiling with cl.exe /Zi, MSVC++10:

push    ebp
mov     ebp, esp
push    ecx
call    j_?func@@YAHXZ  ; func(void)
mov     [ebp+a], eax ; assumes eax contains the return value
xor     eax, eax
mov     esp, ebp
pop     ebp

Of course, this is all undefined behavior.

Leave a Comment