【问题标题】:control reaches end of non-void functions -wreturn-type控制到达非空函数的结尾 -wreturn-type
【发布时间】:2020-03-26 09:12:01
【问题描述】:

这是查找最多四个数字的代码:

#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;
}

但我收到这样的警告:

控制到达非空函数的结尾 -wreturn-type

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

【问题讨论】:

  • 您还没有涵盖函数中的所有案例。只需添加... else { return 0; }
  • 如果没有一个 if 是 true,则不返回任何内容。这是未定义的行为。
  • 问问自己如果abcd都相等会发生什么。
  • @john 好的,但返回 0 不是错误。我刚刚添加了一个可以修复编译错误的示例。然后,OP 会将逻辑应用于他的案例。
  • 顺便说一下,有一个更好的方法来计算最大值。像 max = a;如果 (b) > max max = b;如果 (c> 最大值) 最大值 =c;如果 ( d > 最大值 ) 最大值 = d;返回最大值;

标签: c++


【解决方案1】:

这是一个会导致此警告的简化案例,希望它能明确警告的含义:

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

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

例如,如果 question 的值为 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++ 会发出警告而不产生编译器错误?

这里讨论了这个问题: Why does flowing off the end of a non-void function without returning a value not produce a compiler error?

【讨论】:

    【解决方案2】:

    控制到达非空函数的结尾 -wreturn-type 这个错误是什么意思?为什么会出现这个错误?

    如果你的四个条件都为假,那么函数的返回值是什么?所以编译器会给出警告。

    所以你可以做类似的事情,

    #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 above conditions are false then d is big
        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;
    }
    

    【讨论】:

    • 顺便说一句,我不会过分依赖编译器,意识到条件并不涵盖所有情况,我认为它宁愿看到没有else,这意味着可能存在未涵盖的情况
    【解决方案3】:

    如果一个函数有一个返回值,它return一个值无论如何。因此,如果您将return 绑定到条件语句,则从程序的角度来看,任何可能的条件都必须存在案例。您可能知道您的代码只会为函数提供给定组合之一,但您的编译器不知道。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-29
      相关资源
      最近更新 更多