Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting "control reaches end of non-void function" warning even when I've covered all cases

Why if I have two conditions while both returns the right type in a function as it should be, I am getting an alarm.

control reaches end of non-void function [-Wreturn-type]

bool EtherTrafGen::isGenerator()
{
    if (multipacket) return par("destAddresses").stringValue()[0];
    else if (!multipacket) return par("destAddress").stringValue()[0];
} 

What is the way to correct such an alarm?

like image 402
Mour_Ka Avatar asked Nov 18 '25 03:11

Mour_Ka


1 Answers

Even though control can never reach

bool EtherTrafGen::isGenerator()
{
    if (multipacket) return par("destAddresses").stringValue()[0];
    else if (!multipacket) return par("destAddress").stringValue()[0];
    //here
} 

The compiler can't know that (since it's an else if) and it warns you about potential undefined behaviour if it is reached (maybe another thread modifies multipacket after the first check etc). You can just add a default return value to satisfy the compiler:

bool EtherTrafGen::isGenerator()
{
    if (multipacket) return par("destAddresses").stringValue()[0];
    else if (!multipacket) return par("destAddress").stringValue()[0];
    return false;
}

Or just cut the whole else if since it's either true or false:

bool EtherTrafGen::isGenerator()
{
    if (multipacket) return par("destAddresses").stringValue()[0];
    return par("destAddress").stringValue()[0]; // multipacket must be false here anyway
} 
like image 124
Hatted Rooster Avatar answered Nov 20 '25 17:11

Hatted Rooster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!