控制到达非空函数结束[-Werror=return-type]

control reaches end of non-void function [-Werror=return-type]

本文关键字:-Werror return-type 结束 函数 控制      更新时间:2023-10-16

即使使用默认的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是问题

if((a>b)&&(a>c))
{
    if(a>d)
        return a;
    // what about else?
}

如果您的外部条件是true,而内部条件是false,则不会有任何return情况。

顺便说一下,你的方法是一个非常复杂的方法来解决这个问题,或者至少很难阅读。我会这样做。
#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));
}

也可以用

#include <algorithm>
int max_of_four(int a, int b, int c, int d)
{
    return std::max({a, b, c, d});
}

> " control到达non-void function end [-Werror=return-type] "错误发生在编译阶段,当你的非void函数(定义为返回值)有可能无法返回值时(分支)。虽然,这取决于输入,但它不一定到达那个死胡同。

如果:

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;
}
相关文章: