Optimisations and undefined behaviour
Segher Boessenkool
segher@kernel.crashing.org
Sun Nov 8 19:34:00 GMT 2015
On Sun, Nov 08, 2015 at 08:11:08PM +0100, 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.
The compiler is free to transform it to
int foo(int x) {
int t = x*x*x;
if (x > 1290) {
printf("X is wrong here %d, but we don't care\n", x);
}
return t;
}
because x*x*x does not have any observable behaviour, and then it is
obvious it _can_ remove the printf and conditional. Undefined behaviour
is not observable behaviour.
No?
Segher
More information about the Gcc-help
mailing list