Gcc silently transforms a finite loop to an infinite one

David Brown david.brown@hesbynett.no
Wed Nov 30 06:44:00 GMT 2011


On 29/11/11 16:44, Joseph S. Myers wrote:
> On Tue, 29 Nov 2011, Nadezhda Ivan�vna Vyukova wrote:
>
>> I've explained the customer that by default char is treated
>> as signed char on our platform and therefore this program
>> does not conform ISO C90, as it causes the integer overflow
>> (undefined behavior). But he was not satisfied.
>
> Actually this program does not involve undefined behavior, because the
> increment happens in type int and then implementation-defined behavior
> converting the int to char (which GCC defines as modulo) applies.  See PR
> 35634 which has various discussion of possible approaches for fixing
> this, and patches that introduce vectorizer optimization regressions.
>

With this interpretation, then I can see that the program does not 
involve undefined behaviour.  But I think it should behave differently.

When e is 127 before the loop, the "while (++e)" will promote e from a 
(signed) char to a signed int - giving 127.  This is incremented to 128 
(valid for an int).  The value is stored back to e by modulo truncation, 
which gives -128 for a signed char.  And the value 128 is tested for the 
while loop.

So after printing 127, it should print -128.

This will be followed by -127, -126, ..., -1 when e is -1.

When executing "while (++e)", ++e is now 0 and the loop will exit.


But when compiled with -O2 with "-Wstrict-overflow", the compiler warns 
"assuming signed overflow does not occur when simplifying conditional to 
constant" - and the program runs prints a never-ending sequence of 
positive integers (well, until I control-C'd the program).

Does this mean that there is a bug somewhere, or is it the conversion 
from int value 128 to a signed char that is undefined?

mvh.,

David





More information about the Gcc mailing list