I wonder how C++ behaves in this case:
char variable = 127;
variable++;
In this case, variable now equals to -128. However did the increment operator wrapped the value to its lower bound or did an overflow occurred?
Thanks in advance!
I wonder how C++ behaves in this case:
char variable = 127;
variable++;
In this case, variable now equals to -128. However did the increment operator wrapped the value to its lower bound or did an overflow occurred?
Thanks in advance!
Plain
char
can be either signed or unsigned. If the maximum value is 127, then it must be signed in your implementation.For unsigned types, "overflow" is well defined, and causes wraparound. For signed types, the behavior on arithmetic overflow is undefined (wraparound is typical, but not required). But that actually doesn't apply in this particular case; instead, the value stored in
variable
is implementation-defined.For types narrower than
int
, things are a little more complicated. This:is equivalent to this:
The operands of the
+
operator have the "usual arithmetic conversions" applied to them, which in this case means that both operands are promoted toint
. Sinceint
is more that wide enough to hold the result, there's no overflow; the result is128
, and is of typeint
. When that result is stored back intovariable
, it's converted fromint
tochar
.The rules for overflow are different for conversions than they are for arithmetic operations like "+". For a signed-to-signed or unsigned-to-signed conversion, if the value can't be represented in the target type, the behavior is not undefined; it merely yields an implementation-defined result.
For a typical implementation that uses a 2's-complement representation for signed integer types, the value stored will probably be -128 -- but other behaviors are possible. (For example, an implementation could use saturating arithmetic.)
Another (rather obscure) possibility is that
char
andint
could be the same size (which can happen only ifchar
is at least 16 bits). That can have some interesting effects, but I won't go into that (yet).An overflow occured and results in undefined behavior.
Section 5.5:
The standard goes on to note that integer overflows are, in most implementations, ignored. But this doesn't represent a guarantee.