Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}
like image 342
Alpha Avatar asked Jun 01 '26 15:06

Alpha


1 Answers

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.

like image 169
Ted Lyngmo Avatar answered Jun 03 '26 19:06

Ted Lyngmo