gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 23:32:50 25 4
gpt4 key购买 nike

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

#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. 在计算表达式之前是否发生了到 signed char 的隐式类型转换?

  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 的隐式转换(算术转换 vs. 赋值),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11569669/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com