c++ - int 类型的函数不使用 return C++

标签 c++ return cout endl

如果我有这样的函数:

int addNumbers(int x, int y)
{
    return x + y;
}

如果我这样使用它:

cout << addNumbers(4, 5) << endl;

它将返回并打印9。使用上面相同的 cout 行,如果我注释掉或删除 addNumbers 中的返回,它将返回并打印 1。如果我这样做:

int addNumbers(int x, int y)
{
    int answer = x + y;
    //return x + y;
}

它会自动返回并打印9,而无需我使用return。同样,我可以写 int answer = x;它将返回4。我也可以这样写:

int addNumbers(int x, int y)
{
    int answer = x;
    answer = 1;
    //return x + y;
}

它仍然会返回 4。

到底返回了什么以及为什么?当我使用参数变量时,它只返回 1 以外的值,但它不会返回上一个示例中所示的变量答案,因为我将其更改为 1 并且它仍然返回 x (4)< 的值

最佳答案

§6.6.3 [stmt.return]/p2:

Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior in a value-returning function.

(main() 是一个特殊异常。从 main() 末尾流出相当于 return 0;)

允许的 UB 包括:

  • 返回您“想要”返回的内容
  • 返回一个垃圾值
  • 崩溃
  • 将您的密码发送给黑客
  • 格式化您的硬盘
  • 让你的电脑爆炸并炸断你的腿
  • 召唤鼻恶魔
  • 回到过去并将您的程序修正为正确的事情
  • 创建黑洞
  • ......

但说实话,UB 可以通过各种方式表现出来。例如,给定以下代码:

#include <iostream>
bool foo = false;
int addNumbers(int x, int y)
{
    int answer = x;
    answer = 1;
    //return x + y;
}

int main(){
  if(!foo) {
    addNumbers(10, 20);
    std::cout << 1 << std::endl;
  }
  else {
    std::cout << 2 << std::endl;
  }
}

clang++ at -O2 prints 2

为什么?因为它推断 addNumbers(10, 20); 具有未定义的行为,这使得它可以假设第一个分支从未被采用,并且 foo 始终为 true ,尽管情况显然并非如此。

关于c++ - int 类型的函数不使用 return C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25698481/

相关文章:

c++ - 什么是 "Argument-Dependent Lookup"(又名 ADL,或 "Koenig Lookup")?

c++ - 对函数的调用不明确

java - 缺少带开关的返回语句

c++ - cout C++ 期间出现堆错误

c++ - 字符串不会计算第一部分

c++ - WinCE6 上的 QTcpServer->listen() "protocol type not supported"

c++ - 仅在 vector 末尾打印新行 - "if"循环之外的 "for"语句

c++ - 要引用的默认值,c++

C++ - 返回 0 与返回 -1

printf() 或格式化输出的 C++ 等价物