c - unsigned char 的隐式转换(算术转换与赋值)

标签 c casting

在做某事时遇到了类似于以下的代码:

#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) - 结果将是一个始终大于或等于零的无符号字符。然而,代码按预期运行,我认为我的理解是有缺陷的。所以...

我的问题是:

  1. 在计算表达式之前是否会进行到有符号字符的隐式类型转换?

  2. 是否存在上述代码不起作用的情况(例如,如果无符号值足够大以至于无法用有符号值表示)?

最佳答案

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/

相关文章:

Java 泛型 : casting to ? (或使用任意 Foo<?> 的方法)

c - TCP 回显服务器中的绑定(bind)错误

c - 使用 c 恢复 .raw 文件

c++ - 在初始化列表中转换 shared_ptr

将指针转换为连接

c - volatile 对数组和类型转换的意义

python - cython 中奇怪的整数行为

c - 使用 atoi() 对整数进行输入验证

c - 文件中带有变音符号的 y

ruby-on-rails - Rails 迁移 : tried to change the type of column from string to integer