-4
#include <iostream>
using namespace std;

int main() {
    unsigned char char_values[2] = {0, 255};
    char_values[1] += 1;
    cout << (int)char_values[0] << endl;
    cout << (int)char_values[1] << endl;
    return 0;
}

On this code, I expected:

1
0

Because 255 in decimal is 1111 1111 in binary and 255 + 1 in decimal is 1 0000 0000 in binary. so I thought that char[0] will be affected by char[1] because of overflow but result is:

0
0

Does overflow affects other variables?

Joris Timmermans
  • 10,814
  • 2
  • 49
  • 75
Users2530
  • 9
  • 3
  • 5
    That is not valid C++... – Rakete1111 Jan 22 '18 at 15:29
  • 4
    When creating a [Minimal, Complete, and Verifiable Example](http://stackoverflow.com/help/mcve) that is supposed to build, make sure it actually does. – Some programmer dude Jan 22 '18 at 15:30
  • How did you get this to print anything? [I only get errors](http://coliru.stacked-crooked.com/a/f3c8390ea69aea7c). – nwp Jan 22 '18 at 15:31
  • 4
    As for your problem, no. Unsigned integer overflow does only wrap the overflowed value, nothing else happens. If you treated the array as a single `unsigned short` value then it would be like you expected (depending on [*endianness*](https://en.wikipedia.org/wiki/Endianness) of course). – Some programmer dude Jan 22 '18 at 15:31
  • 2
    **Are you sure this code compiles???** – iBug Jan 22 '18 at 15:33

1 Answers1

5

If an unsigned integral type like unsigned char overflows, then the result is "truncated" to the bits provided by that data type (actually it is defined in terms of modulo MAX_XXX+1 with XXX being the repspective data type). So there is no effect to variables / memory before or after the "overflowing" object; and 255+1 is 256, and 256 truncated to the lower significant 8 bits gives 0.

Please note that an overflow on signed integral types behaves completely different, i.e. it is undefined behaviour then.

Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58
  • Strictly speaking, the standard says "This implies that unsigned arithmetic does not overflow because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting unsigned integer type." (3.9.2, note 47, http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3690.pdf) – Joris Timmermans Jan 22 '18 at 15:45