I recently wrote a post:
Weird Error in C++ Program: Removing Printout Breaks Program
...in which I was trying to solve a seemingly baffling problem, in which removing a cout statement would break my program.
As it turned out, my problem was that I forgot to return my true/false success flag that I was later using for logic.
But apparently SOMETHING was being returned and that something was always true if I left that cout in, but would seemingly "magically" become false when I took it out.
My question for you all is:
What determines what a c++ function return when no return command is executed within the function? Is there any logic to it?
Obviously forgetting your return type is a bad idea. In this case, though, it was largely due to the nature of my program -- a quick hack job. I later decided that it wasn't worth the effort to include implement an algorithm to determine the success/failure of the function call -- but accidentally left behind the code dependent on the return.
Bafflingly g++ gave me no warnings or errors when compiling the executable like so:
g++ main.cc -g -o it_util
My version is: g++ (GCC) 4.1.2 20080704 (Red Hat 4.1.2-44)
Again, to save others future frustration in case they make the same silly mistake and are met with the same seemingly erratic behavior, can anyone cast light on where a function without a return gets its return value from??
Thanks!!
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
retn
Of course, this is all undefined behavior.
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