控件到达非void函数的末尾-wreturn类型



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

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

但我收到这样的警告:

控制到达非无效功能的末尾-扭转型

这个错误意味着什么
为什么会出现此错误?

下面是一个导致此警告的简化案例,希望它能使警告的含义变得清晰:

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

你可能在对自己说;但我确实涵盖了所有的案件!其他情况都不可能"这在逻辑上是正确的,但编译器并不知道这一点。它不构建一个>b、 b<a等

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

// 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函数的末尾流出不会产生编译器错误?

控件到达非void函数的末尾-wreturn类型这个错误意味着什么?为什么会出现此错误

如果您的四个条件为假,那么函数将返回什么值?,因此编译器会发出警告

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

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

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

最新更新