当函数中未指定返回值时,C++ progs 如何获得它们的返回值?

How do C++ progs get their return value, when a return is not specified in the function?(当函数中未指定返回值时,C++ progs 如何获得它们的返回值?)

本文介绍了当函数中未指定返回值时,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++函数返回的内容?有什么逻辑吗?

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

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.

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

本文标题为:当函数中未指定返回值时,C++ progs 如何获得它们的返回值?

基础教程推荐