当函数中没有指定返回值时,C ++程序如何获得它们的返回值? [英] How do C++ progs get their return value, when a return is not specified in the function?

查看:289
本文介绍了当函数中没有指定返回值时,C ++程序如何获得它们的返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我最近写了一篇文章:

http://stackoverflow.com/questions/3452355/weird-error-in-c-program-removing-printout-breaks-program

...在其中我试图解决一个看似困惑的问题,其中删除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.

但显然SOMETHING被返回,

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 ++函数返回时没有返回命令在函数内执行?它有什么逻辑吗?

显然,忘记你的返回类型是一个坏主意。在这种情况下,虽然,这主要是由于我的程序的性质 - 一个快速的黑客工作。我后来决定,不值得努力包括实现一个算法来确定函数调用的成功/失败 - 但意外留下的代码依赖于返回。

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 ++在编译可执行文件时没有给出警告或错误:

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 (Red Hat 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.

这篇关于当函数中没有指定返回值时,C ++程序如何获得它们的返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆