Mod operator with unsigned char

c, modulo

Solution

First of all, in C, `%` is not the modulo operator. It is the remainder operator.

Otherwise, you're right that integer promotion happens. `uint8_t` is implicitly converted to an `int` when it appears as the argument of an arithmetic operator.

So when `x` reaches 0, then `x - 1` will become -1. Then, `-1 % 10` is -1 (and not 9), and -1 assigned to `uint8_t` yields 255 (since unsigned integer overflow is defined in terms of modulo arithmetic).

Problem

I found a very strange behavior using the modulo operator. Given the following code: ``` #include <stdio.h> #include <stdlib.h> #include <stdint.h> int main() { uint8_t x = 2; uint8_t i; for(i=0; i<5; i++) { x = (x - 1) % 10; printf("%d ", x); } printf("\n"); } ``` I expect as a result `1 0 3 4 2`, but instead I get `1 0 255 4 3`. I think it has something to do with the integral promotion, but I don't understand how the conversion is done.

Original source

Related problems