Question

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.

Was it helpful?

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).

OTHER TIPS

I'm not clear on why you expected a 3 after the 0; mathematically, 0-1 yields -1, and the remainder of -1 divided by 10 is either -1 or 9 depending on your definition of remainder.

With that said, what happens in your step where x transitions from 0 to 255 is that 0-1 yields -1, and C's % operator defines remainder such that you get a result of -1. The key is what happens next: you assign -1 into a variable of type uint8_t. Since -1 is outside the range of representable values (0 to 255) and the type is unsigned, the conversion takes place by reducing the value modulo 256 (one plus the max value) into the range, thus yielding 255.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top