previous | start | next

C Integer Arithmetic!

Consider the integer type: unsigned char with values: 0 to 255.

What is 255 + 1 as an unsigned char? Not 256.

255 + 1 is out of range - overflow.

But no error occurs, it "wraps around" to get the next value, which is 0:

      0 1 2 ...   254 255
   

The mod operator, % provides a way of calculating how C computes values of unsigned integers that overflow.

There are 256 possible unsigned char values. The mod operator x % 256 will give a value in the range 0 to 255. Just what is required of the unsigned char type.

(255 + 1) % 256 = 0


previous | start | next