cunsigned-charinteger-promotioncompound-assignment

What does *= do?


Hey I am kinda new to C and I wanted to ask why this prints out 4 instead of 260?

#include <stdio.h>

int main()
{
    unsigned char x = 130;
    x *= 2;
    printf("%d\n", x);
}

Solution

  • The *= operator is called multiplication assignment operator and is shorthand for multiplying the operand to the left with the operand to the right and assigning the result to the operand to the left. In this case, it's the same as:

    x = x * 2;
    

    Here integer promotion first takes place and the result of x * 2 is indeed 260.

    However, an unsigned char can usually only carry values between 0 and 255 (inclusive) so the result overflows (wraps around) when you try assigning values above 255 and 260 % 256 == 4.