Bit shift supports unsigned char to int

The following code:

unsigned char result; result = (result << 4 ); 

Compiled with gcc version 4.6.4 (Debian 4.6.4-2), a warning appears with the -Wconverersion flag

warning: converting to 'unsigned char' from 'int' may change its value [-Wconversion]

Why is this?

+4
source share
3 answers

Because the standard says so. The operands for binary operators go through a whole campaign in which everything less than int raised to int ; the results of the type int operation. And if the original value was, say, 0x12 , the results will be 0x120 and assigning it an unsigned char will cause the value to change. (The assigned value will be 0x20 .) From where the warning appears.

EDIT:

From the standard (Β§5.8 Shift operators): β€œThe operands must have an integral or non-listed type of listing and integral promotions. The type of result is the result of an advanced left operand.” Unlike other binary operators, there is no effort to find a common type from two operators: The result type is the left operand, period. But integral promotion is still happening: unsigned char will be up to int (or up to unsigned int if int has size 1).

+7
source

Since the int value may be larger than it can fit in an unsigned char .

Think about what happens when result is 255 (i.e. 0xff ). Shifting four bits to the left will make it 4080 (or 0xff0 ). How can the compiler compress this value back to result ? It cannot, so it just trims it to 240 ( 0xf0 ). In other words, the value of the integer operation result << 4 can be changed.

+1
source

All arithmetic and logical operators perform "integral advancements" in their arguments. Integral stocks convert types that are less than int (e.g. unsigned char ) to int or unsigned int . You will see the same if you replace << with + .

Oh, and brackets are not needed.

0
source

Source: https://habr.com/ru/post/1489903/


All Articles