VIKAS. BHAT VIKAS. BHAT - 1 month ago 26
C++ Question

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

Even after using default else statement I am getting this error

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

Answer

Your first if is the problem

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

If your outer condition is true, but the inner condition is false, it will not have any return case.

By the way, your method is a very convoluted way to solve this, or at least difficult to read. I would do something like this.

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

You could also use

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