Optimisations and undefined behaviour
David Brown
david.brown@hesbynett.no
Sun Nov 8 19:34:00 GMT 2015
On 08/11/15 20:11, Florian Weimer wrote:
> On 11/06/2015 01:32 PM, David Brown wrote:
>> How about this case:
>>
>> int foo(int x) {
>> if (x > 1290) {
>> printf("X is wrong here %d, but we don't care\n", x);
>> }
>> return x*x*x;
>> }
>>
>> The compiler can eliminate the check and the printf.
>
> I don't think the compiler can do that because printf has an externally
> visible effect, which is sequenced before the undefined behavior, so
> this program transformation would not be permitted under the as-if rule.
>
My understanding (and correct me if it's wrong) is that undefined
behaviour is a feature of a program, rather than just part of it - i.e.,
if code reaches something that causes undefined behaviour, the effect of
the whole program is undefined. This means that if the compiler knows
that it is going to hit an integer overflow, it can affect the course of
things that would have happened without that undefined behaviour.
If I am wrong here (or at least, if the gcc developers think I am wrong
- I'm interested in the compiler practice more than the hypothetical
theory), then I will be happy. That would give undefined behaviour a
limited scope - it will not be able to act backwards through observable
behaviour (outside calls, volatile accesses, etc.).
More information about the Gcc-help
mailing list