当函数中没有指定返回值时,C++ progs 如何获得它们的返回值?
我最近写了一个帖子:
C++ 程序中的奇怪错误:删除打印输出中断程序
...我试图解决一个看似令人费解的问题,其中删除 cout 语句会破坏我的程序.
...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.
但显然有些东西被退回了,如果我把那个 cout 留在里面,那东西总是正确的,但当我把它拿出来时,似乎神奇地"变成了假.
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.
我的问题是:
当函数内没有执行返回命令时,什么决定了 c++ 函数返回什么?有什么逻辑吗?
显然忘记返回类型是个坏主意.不过,在这种情况下,这主要是由于我的程序的性质――一个快速的 hack 工作.后来我决定不值得努力实现一个算法来确定函数调用的成功/失败――但不小心留下了依赖于返回的代码.
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.
编译可执行文件时,g++ 没有给我任何警告或错误,如下所示:
Bafflingly g++ gave me no warnings or errors when compiling the executable like so:
g++ main.cc -g -o it_util
我的版本是:g++ (GCC) 4.1.2 20080704(红帽 4.1.2-44)
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??
谢谢!!
推荐答案
在 x86 调用约定中,整数和指针的返回值在 EAX 寄存器上.下面是一个例子:
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();
}
用cl.exe/Zi
编译,MSVC++10:
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.
相关文章