控制到达非 void 函数末尾 -wreturn-type

2024-05-18

这是查找四个数字中的最大值的代码:

#include <iostream>
#include <cstdio>
using namespace std;

int max_of_four(int a,int b,int c,int d) {
    if(a>b&&a>c&&a>d)
    return a;
    else if(b>a&&b>c&&b>d)
    return b;
    else if(c>a&&c>b&&c>d)
    return c;
    else if(d>a&&d>c&&d>b)
    return d;
}

int main() {
  int a,b,c,d;
  scanf("%d %d %d %d",&a,&b,&c,&d);
  int ans;
  ans=max_of_four(a,b,c,d);
  printf("%d",ans);
  return 0;
}

但我收到这样的警告:

控制到达非 void 函数末尾 -wreturn-type

这个错误是什么意思?
为什么会出现这个错误?


这是一个会导致此警告的简化情况,希望它能让警告的含义变得清晰:

// Not allowed - Will cause the warning
int answer(int question)
{
    if( question == 1 )
        return 100;
    else
        if ( question == 2 )
            return 200;  
}

如果问题不是1也不是2怎么办?

例如,如果问题的值为 3 或 10 该怎么办?

函数会返回什么?

它是未定义的,并且是非法的。这就是警告的含义。

当返回值的函数结束时,必须为所有情况定义它返回的值。

但你的情况与此更相似,它仍然会产生警告:

// Not allowed - still causes the warning
int max_of_two(int a, int b)
{
    if( a>b )
        return a;
    else
        if ( b>=a ) // we covered all logical cases, but compiler does not see that
            return b;  
}

您可能会对自己说:“但我确实涵盖了所有情况!没有其他情况是可能的!” 这在逻辑上是正确的,但编译器不知道这一点。它不会构建 a>b、b

那么如何纠正这个错误呢?让编译器更清楚地知道不可能有其他情况。在这种情况下,正确的代码是:

// OK - no warning
int max_of_two(int a, int b)
{
    if( a>b )
        return a;
    else  // The compiler now knows for sure that no other case is possible
        return b;  
}

更有趣的问题是为什么 C++ 会发出警告而不产生编译器错误?

这个问题在这里讨论:为什么在不返回值的情况下流出非 void 函数的末尾不会产生编译器错误? https://stackoverflow.com/questions/1610030/why-does-flowing-off-the-end-of-a-non-void-function-without-returning-a-value-no

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

控制到达非 void 函数末尾 -wreturn-type 的相关文章

随机推荐