C++ 控件到达非无效函数的末尾[-Werror=返回类型]
即使在使用默认的else语句之后,我也会遇到这个错误C++ 控件到达非无效函数的末尾[-Werror=返回类型],c++,if-statement,return-type,C++,If Statement,Return Type,即使在使用默认的else语句之后,我也会遇到这个错误 int max_of_four(int a, int b, int c, int d) { if((a>b)&&(a>c)) { if(a>d) return a; } else if((b>c)&&(b>d)) { return b; } else
int max_of_four(int a, int b, int c, int d)
{
if((a>b)&&(a>c))
{
if(a>d)
return a;
}
else if((b>c)&&(b>d))
{
return b;
}
else if(c>d)
{
return c;
}
else
return d;
}
如果问题出在您的第一个
if((a>b)&&(a>c))
{
if(a>d)
return a;
// what about else?
}
如果外部条件为true
,而内部条件为false
,则不会有任何返回
大小写
顺便说一句,你的方法是一个非常复杂的方法来解决这个问题,或者至少很难阅读。我会这样做
#include <algorithm>
int max_of_four(int a, int b, int c, int d)
{
return std::max(std::max(a, b), std::max(c, d));
}
#包括
int max_of_four(int a,int b,int c,int d)
{
返回std::max(std::max(a,b),std::max(c,d));
}
你也可以使用
#include <algorithm>
int max_of_four(int a, int b, int c, int d)
{
return std::max({a, b, c, d});
}
#包括
int max_of_four(int a,int b,int c,int d)
{
返回std::max({a,b,c,d});
}
控件到达非无效函数的末尾[-Werror=返回类型]“
当非void函数(定义为返回值)可能无法返回值时(分支),编译阶段会发生错误。尽管取决于输入,但它不一定会到达死胡同。如果:
这个错误不是指出了一个特定的行号吗?它指向你函数定义的最后一个支撑吗?为什么Heck是这个值?6?这个答案有点混乱,特别是对于C++新手来说。有没有一种更直接的表达方式?
int max_of_four(int a, int b, int c, int d)
{
if((a>b)&&(a>c))
{
if(a>d)
return a;
else
return d;
}
else if((b>c)&&(b>d))
{
return b;
}
else if(c>d)
{
return c;
}
else
return d;
}