Reputation: 167
With respect to return values:
func()
{
while(1)
{
/* do stuff here */
if(error1) exit(0);
if(error2) break;
}
/* no return statement anywhere in func() */
}
but the caller checks the return code of func()
if(func()) {/* error handling */}
what'd nice would be someone to confirm that the return value of func()
does not default to anything and is junk. And that this is true for all these:
void func()
int func()
, which is not featuring a return statement at all, or with a plain return;
.func()
, unspecified return type, which i understand defaults to returning int.thanks..
Upvotes: 0
Views: 619
Reputation: 20980
The return value of a function is generally returned by the first register of the processor, e.g. EAX for x86 based or r0 for ARM based processor. It is compiler specific, but that is more or less standard.
e.g.return 10;
in C will get translated to
mov eax 10 ; pseudo code
ret ; pseudo code
in assembly for x86 based processor.
& While checking the return value, it will just check the eax register. Whatever is contained in that register is considered as return value by caller.
SO... If you return without a value (simple return;
) or it's a void function, whatever value is contained in EAX just before ret
statement in assembly, is taken as return value by the caller.
For ARM
based processor, replace EAX
by r0
in above answer. :-)
I used this fact as a hack for below function ;-)
void* getStackTop(){
asm("mov eax esp");
}
To check how exactly it works while translating from C to ASM, write a simple code as below:
int testfn(int unused){
int unused2=unused; // Check how input is passed
return 10; // Check how output is returned
}
& then compile it with gcc -S
. (or with your compiler with some flag that will generate only assembly.)
I am not sure how it returns float/struct values. Probably it returns a pointer to struct & entire returned struct is memcpy'ed under the hood, while translating to asm. Someone may rectify :-)
Upvotes: 2
Reputation: 33283
Note: This answer applies to C89 (and earlier versions).
void func()
specifies a functions that doesn't return a value. In this case if (func())
should result in a compile error.
int func()
and func()
are equivalent and return an integer value.
If no value is provided by a return statement the result is undefined, and the compiler issues a warning if the warning level is high enough.
In practice, most compilers will generate code that returns whatever is in the register or memory position used for the return value.
Upvotes: 3
Reputation: 214860
The code you posted in not valid C code, since the C99 standard.
If you are using an obsolete compiler that implements the C90 standard, it would compile and the default type would then be int. I believe omitting the return statement from such a function would result in undefined behavior, though I can't cite the C90 standard.
Upvotes: 0