在做某事时遇到了类似于以下的代码:
#define MODULUS(a,b) ((a) >= 0 ? (a)%(b) : (b)-(-a)%(b))
unsigned char w;
unsigned char x;
unsigned char y;
char z;
/* Code that assigns values to w,x and y. All values assigned
could have been represented by a signed char. */
z = MODULUS((x - y), w);
据我了解,算术 (x - y)
将在任何类型转换之前完成,并且宏将始终计算为 (a)%(b)
- 结果将是一个始终大于或等于零的无符号字符。然而,代码按预期运行,我认为我的理解是有缺陷的。所以...
我的问题是:
在计算表达式之前是否会进行到有符号字符的隐式类型转换?
是否存在上述代码不起作用的情况(例如,如果无符号值足够大以至于无法用有符号值表示)?
最佳答案
Does an implicit type conversion to signed char occur before the expression is evaluated?
不,到 int
的转换发生在表达式 x - y
计算之前。因此结果可能为负。
Is there a situation (for example, if the unsigned values were large enough that they could not be represented by a signed value) where the above code would not work?
如果sizeof int == 1
,整数提升会将unsigned char
提升为unsigned int
,这可能会产生错误结果是因为在按 w
取模之前,由于无符号算术而执行了按 UINT_MAX + 1
取模。
¹ 默认整数提升。
关于c - unsigned char 的隐式转换(算术转换与赋值),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11569669/