在-255到255范围内未定义带符号的char溢出吗? [英] Is signed char overflow undefined within the range -255 to 255?
问题描述
在C99模式下,根据GCC,以下代码是否为未定义行为:
Is the following code undefined behavior according to GCC in C99 mode:
signed char c = CHAR_MAX; // assume CHAR_MAX < INT_MAX
c = c + 1;
printf("%d", c);
推荐答案
签名字符
溢出的确会导致未定义的行为,但这不是发布的代码中发生的情况。
signed char
overflow does cause undefined behavior, but that is not what happens in the posted code.
With c = c +1
,整数提升在加法之前执行,因此表达式中的 c
被提升为 int
在右边。由于 128
小于 INT_MAX
,因此这种添加不会发生意外。请注意, char
通常比 int
窄,但在罕见的系统 char
和 int
的宽度可以相同。无论哪种情况,在算术表达式中, char
都被提升为 int
。
With c = c + 1
, the integer promotions are performed before the addition, so c
is promoted to int
in the expression on the right. Since 128
is less than INT_MAX
, this addition occurs without incident. Note that char
is typically narrower than int
, but on rare systems char
and int
may be the same width. In either case a char
is promoted to int
in arithmetic expressions.
然后对 c
进行赋值时,如果普通 char
是 unsigned
在所讨论的系统上,相加的结果小于 UCHAR_MAX
(必须至少为255),并且该值在转换并分配给 c
。
When the assignment to c
is then made, if plain char
is unsigned
on the system in question, the result of the addition is less than UCHAR_MAX
(which must be at least 255) and this value remains unchanged in the conversion and assignment to c
.
如果不是普通的 char
是带符号的
,加法的结果在赋值前会转换为带符号的字符
的值。在这里,如果加法的结果不能用带符号的字符
表示,则转换是实现定义的,或者引发实现定义的信号。 SCHAR_MAX
必须至少为127,如果是这种情况,那么当纯 char
是签名的
。
If instead plain char
is signed
, the result of the addition is converted to a signed char
value before assignment. Here, if the result of the addition can't be represented in a signed char
the conversion "is implementation-defined, or an implementation-defined signal is raised," according to §6.3.1.3/3 of the Standard. SCHAR_MAX
must be at least 127, and if this is the case then the behavior is implementation-defined for the values in the posted code when plain char
is signed
.
该行为不是未定义代码的行为,而是实施定义。
The behavior is not undefined for the code in question, but is implementation-defined.
这篇关于在-255到255范围内未定义带符号的char溢出吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!