如果分配的值占用的类型多于可用类型 space,会发生什么情况?

What happens to a value assigned to take up more than a types available space?

例如

uint8_t value = 256;

调试输出:

0

我听说它会进行某种截断?我不知道具体如何,感谢任何链接。

在无符号整数类型的情况下,最低的适当位数存储在变量中。 (布赖恩的回答涵盖了我在这里所说的一切。)

例如,unsigned char a = 257 将导致 a=1

编译器(在本例中为gcc)应该在您进行此类赋值时警告您,例如filename.c:line:column: warning: overflow in implicit constant conversion [-Woverflow].

根据[conv.integral]

If the destination type is unsigned, the resulting value is the least unsigned integer congruent to the source integer (modulo 2^n where n is the number of bits used to represent the unsigned type). [ Note: In a two’s complement representation, this conversion is conceptual and there is no change in the bit pattern (if there is no truncation). — end note ]

If the destination type is signed, the value is unchanged if it can be represented in the destination type (and bit-field width); otherwise, the value is implementation-defined.

因此,对于您的示例,您将可靠地得到零;如果您使用 int8_t 而不是 uint8_t,结果将由实现定义。 (相反,如果对有符号整数的操作 溢出 ,结果是未定义的行为。为什么不一致?我不知道。)

我会试着和你一起理解它。

uint8_t是一个8位的数据类型,也就是一个字节。它有 8 个插槽,可以是 101111 1111 将是 255。因此,如果您向其添加一个,它会继续结转。 255 + 1 在二进制中是 1 0000 0000,但由于数据类型只能存储 8 位,因此它去掉了 1,变成 0000 0000,转换为整数值 0

至少,我是这么理解的。