控制到达非void函数的结尾[-Werror = return-type]

Vik*_*hat -5 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 if(c>d)
    { 
        return c; 
    }
    else 
        return d;
}
Run Code Online (Sandbox Code Playgroud)

Cor*_*mer 10

你的第一个if问题是

if((a>b)&&(a>c))
{
    if(a>d)
        return a;
    // what about else?
}
Run Code Online (Sandbox Code Playgroud)

如果你的外在条件是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));
}
Run Code Online (Sandbox Code Playgroud)

你也可以用

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