Efficient detection of signed overflow?
me22
me22.ca@gmail.com
Mon Nov 30 15:59:00 GMT 2009
2009/11/30 Mark Dickinson <dickinsm@gmail.com>:
>
> In practice, yes, I think so. In theory, no: the result of the conversion is
> implementation defined for numbers outside the range of the signed type.
> (C99 6.3.1.3). But I'd be surprised if any implementation on a two's
> complement machine does anything other than just preserve the bit
> pattern, as you'd expect.
>
Thanks for clarifying.
I guess I was thinking of C++ aliasing rules (3.10/15), where reading
a signed through an unsigned or vice versa is allowed, but as you
point out, that doesn't define their value (4.7/3 does).
FWIW, though, I just checked in llvm-gcc, and both of these compile to
the same IR:
int foo(int i) {
return i < 0;
}
int foo(unsigned i) {
return i >= (1 << (sizeof(unsigned)*CHAR_BIT-1));
}
So it might not be a pessimization after all to be strictly portable.
~ Scott
(Sorry if using LLVM as an example is heresy here; it's easier for me
to test while I'm on a machine without GCC :P)
More information about the Gcc-help
mailing list