c++ - C++ 中的函数行为

标签 c++ function

我有以下代码:

int Fun(int x, int y)
{
    if(x<y)
        return 1;
}
int main ()
{

    cout<<Fun(6,2)<<endl;
}

这段代码的输出是6(x的值)!!我不知道为什么会出现这种行为...任何人都可以向我解释一下。

提前致谢。

最佳答案

这里有一个 Undefined behavior就像已经说过的那样。

正如 C++11 标准中所述:

6.6.3 The return statement [stmt.return]

  1. [..] 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.

解释:

int Fun(int x, int y)
{
    if ( x < y ) // if this condition is false, then no return statement
        return 1;
}

如何解决这个问题?

int Fun(int x, int y)
{
    if ( x < y )
    {
        return 1;
    }
    return 0;  // <-- Fix the error
}

注意:您的编译器至少应该给您一个警告……您是否忽略了它? (类似于“并非所有控制路径都返回一个值”)

关于c++ - C++ 中的函数行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22784594/

相关文章:

javascript - 三个数字的最大值 DOM 操作

JavaScript 让独立的函数在不定义 new 的情况下工作

c++ - 将库导入我的 C++ 项目时出现问题,如何解决?

c++ - 在 ROI 中使用 findContours,轮廓坐标错误

javascript - JavaScript 中 Function 类的使用

c# - 显示消息框后如何停止功能

c++ - boost.build 与 boost.python

c++ - 可变参数模板重载解析

c++ - binary_log_types.h : No such file or directory

c - 是否可以将 "on the fly"数组传递给 C 函数?