How assignment from int to char works in C?

后端 未结 1 1324
栀梦
栀梦 2021-01-20 22:16

What happens when you assign an int to a char in C? Does it always just ignore the extra bits on the left?

Example (4 bytes int):

unsigned char c = 0         


        
1条回答
  •  隐瞒了意图╮
    2021-01-20 22:47

    Typically, this is exactly what happens. Section 6.3.1.3 of the ISO/IEC 9899:2011 standard prescribes what has to happen in this case:

    6.3.1.3 Signed and unsigned integers

    1. When a value with integer type is converted to another integer type other than _Bool, if the value can be represented by the new type, it is unchanged.
    2. Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.60)
    3. Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.

    60) The rules describe arithmetic on the mathematical value, not the value of a given type of expression.

    Your case falls under item 2 above (since your character is declared as unsigned). In a typical computer arithmetic, the result will be exactly as you described.

    0 讨论(0)
提交回复
热议问题