c++ - 控制到达非空函数的结尾 -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(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 怎么办?
例如,如果 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<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 函数的末尾流出不会产生编译器错误?
推荐阅读
- flutter - 当我将 id 作为 DropdownMenuItem | 中的值访问时,可搜索的下拉搜索不起作用 扑
- powerbi - Power BI 服务中的数据源凭据和计划刷新灰显
- c# - '可查询
' 不包含 'FindAsync' 的定义 - python - statsmodels glm fit_constrained '无法识别的令牌'
- laravel - 为什么 laravel 8 中的 foreach 不起作用,它没有循环
- postgresql - 根据表大小(显然)使用索引进行查询
- json - 添加了请求描述 | AssertionError: 预期 [] 的长度大于 0 但得到 0?
- flutter - 转换列表