C语言中*=运算符的作用是什么?以及为何unsigned char变量运算后输出4而非260?
Hey there! Let's tackle your two C language questions clearly:
*= operator do in C? The *= is a compound assignment operator in C. It’s a shorthand way to multiply a variable by a value and assign the result straight back to that same variable.
Put simply, x *= y works exactly like x = x * y—the only tiny difference is that the left-hand variable x is only evaluated once, though this rarely matters for basic variable usage.
Here’s a quick example to make it concrete:
int score = 7; score *= 2; // Equivalent to score = score * 2; printf("%d", score); // Outputs 14
Awesome question—this is a super common gotcha for C beginners, and it all comes down to how unsigned integer types handle values outside their range! Let’s break it down step by step:
First, unsigned char is an 8-bit unsigned integer type. That means it can only hold values from 0 to 255 (since 2^8 - 1 = 255). Your initial value 130 fits fine, but when you do x *= 2, you end up with 260—way beyond the type’s maximum limit.
For unsigned integers in C, overflow behavior is strictly defined: the value wraps around using modulo 2^n, where n is the number of bits in the type. For 8-bit unsigned char, that’s modulo 256.
Calculating 260 modulo 256 gives us 4 (256 * 1 = 256, 260 - 256 = 4)—that’s why your printf call outputs 4 instead of 260.
If you want to get the expected 260, just switch to a larger integer type that can hold the value, like int (which is typically 32 bits, more than enough for this case):
#include <stdio.h> int main() { int x = 130; x *= 2; printf("%d\n", x); // Now outputs 260 }
内容的提问来源于stack exchange,提问作者Alpha

