The simplest example is signed integer overflow. Causing a signed integer to wrap in C is undefined behavior. GCC exploits this by optimizing out checks which would old be true for wrapping. (It does this when enough compile-time constants are involved.)
Here's an example. Technically this should print "less than zero", but it doesn't on most (all?) version of gcc 4.
#include <stdio.h>
#include <limits.h>
main()
{
signed int si = INT_MAX;
if (si+1 < 0)
printf("Less than zero\n");
else
printf("Greater than or equal to than zero\n");
return 0;
}
When wrapping is 'undefined', that means that adding one to a variable can never result in that variable being less than 0. GCC exploits that "Fact" to optimize this code... even though it breaks it from what we would expect based on our understanding of the hardware.
Technically it should do whatever the compiler pleases, because it's undefined behaviour. That's the very definition of what undefined behaviour is.
I know this seems trivial, but it's a very important distinction. New (and old) programmers need to recognize that just because some compilers may give you some convenient functionality doesn't mean that's what it should or must do.
0
u/[deleted] Jan 21 '13
[deleted]