vcx34178
vcx34178

Reputation: 991

What is this C++ warning - control reaches end of non-void function

I am writing this function definition.

#include<iostream>

int abs_fun(int x);

int main()
{
    int i =abs_fun(0);
    std::cout<<i;
    return 0;
}

int abs_fun(int x)
{
    if (x<0)
        return -x;
    else if(x>=0) //warning
        return x;
}

I am compiling the code using g++ -Wall -Wconversion -Wextra p4.cpp -o p4 and getting warning at the end of abs_fun() as warning: control reaches end of non-void function [-Wreturn-type] } If I just write else instead of else if, then warning goes away. Any suggestions why does warning appear?

Upvotes: 0

Views: 1296

Answers (3)

HolyBlackCat
HolyBlackCat

Reputation: 96430

Because the compiler is not smart enough (or just doesn't bother trying) to understand that one of the returns is always reached.

Upvotes: 5

Fran&#231;ois Andrieux
Fran&#231;ois Andrieux

Reputation: 29022

In the case of an if and else, if both the if and else branch return you can be sure that something returns in all cases.

In your case, it requires an analyses to determine that the conditions fully cover all possible use cases which the compiler is not required to do. In this case it's pretty straight forward, but consider more complicated conditions. If such simple conditions were required to be analyzed, it would be a case of "where do we draw the line?" in terms of what complexity should the compiler be expected to analyze.

Upvotes: 2

Incomputable
Incomputable

Reputation: 2208

The problem is that all control paths should either throw exception or return some value. Doing otherwise is undefined behavior, so compiler wants to warn you about that. In your case, compiler cannot prove that all execution paths lead to return/exception.

Why?

Because doing the check is expensive. Sometimes it might not even be possible. As a result, compiler just doesn't have such feature.

In which cases?

Well, this is more about discrete math.

Upvotes: 0

Related Questions