gcc warn unreached else {}

Jonny Grant jg@jguk.org
Thu Jul 9 15:15:46 GMT 2020



On 09/07/2020 16:00, Xi Ruoyao wrote:
> On 2020-07-09 10:45 +0100, Jonny Grant wrote:
>> Hello!
>>
>> There is an example below, (my code is not like this example below). I'm
>> reporting a possible issue, and asking if there is a way to detect it in code
>> bases. If it's a real issue I can file a bug report on Bugzilla.
>>
>> Can gcc warn where code will not get to the 'return 3;' below?
>>
>> Cheers, Jonny
>>
>>
>> int main(void)
>> {
>>     const int i = 1;
>>     if(1 == i)
>>     {
>>         return 1;
>>     }
>>     else if(1 != i)
>>     {
>>         return 2;
>>     }
>>     else
>>     {
>>         return 3;
>>     }
>> }
> 
> Generally finding all the branches in a program impossible to be executed is
> unsolvable.  Even in a program without any loop it's still NP-hard.
> 
> For some "simple" cases maybe we can implement some heuristics, or use a brute
> force approach (as a part of -fanalyzer).  But I doubt if these simple cases are
> really useful.

Thank you for your reply.
Yes, it would be useful to see more warnings output.

I see this situation every few weeks in code bases upon manual review. The simple case is where it is boolean as above, and is just values, and the else if() the inverse.

The compiler actually generated assembler that returns '1', so it did strip out the unused branches.

As two side questions:
-- Is there anyway to see which branches are removed?
-- Is there anyway to force the compile to keep all branches? (even those it believes will never be executed).

Cheers, Jonny


More information about the Gcc-help mailing list