My questions are divided into three parts
Question 1
Consider the below code,
#include
using namespace std;
i
OK, so this was almost six years ago and the question is answered. Still I feel that there are some bits that have not been adressed to my satisfaction, so I add a few comments, hopefully for the good of future readers of this discussion. (Such as myself when I got a search hit for it.)
The OP specified using gcc 4.1.2 without any special flags. I assume the absence of the -O
flag is equivalent to -O0
. With no optimization requested, why did gcc optimize away code in the reported way? That does seem to me like a compiler bug. I also assume this has been fixed in later versions (for example, one answer mentions gcc 4.5 and the -fno-strict-overflow
optimization flag). The current gcc man page states that -fstrict-overflow
is included with -O2
or more.
In current versions of gcc, there is an option -fwrapv
that enables you to use the sort of code that caused trouble for the OP. Provided of course that you make sure you know the bit sizes of your integer types. From gcc man page:
-fstrict-overflow ..... See also the -fwrapv option. Using -fwrapv means that integer signed overflow is fully defined: it wraps. ... With -fwrapv certain types of overflow are permitted. For example, if the compiler gets an overflow when doing arithmetic on constants, the overflowed value can still be used with -fwrapv, but not otherwise.