c - 具有有符号和无符号整数的表达式

标签 c

添加有符号和无符号值时,我们遵循这两条规则(来自 https://stackoverflow.com/a/2280810/1073672 )

Otherwise, if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type.

Otherwise, if the type of the operand with signed integer type can represent all of the values of the type of the operand with unsigned integer type, then the operand with unsigned integer type is converted to the type of the operand with signed integer type.

上述哪些规则将被触发:

unsigned int ui = 4;
ui = ui + 532; 

最佳答案

常量的类型532int ,已签名。

查看第一条规则,从unsigned int开始和int具有相同的等级,则无符号类型的等级大于或等于有符号类型的等级。第一条规则匹配。签名532转换为unsigned int添加之前。

即使第一条规则不匹配,添加也无法匹配第二条规则,因为签名 int无法表示 unsigned int 的所有值。 (可能的带符号 intunsigned int 的数量相同,但例如, -1 是带符号 int 但不是 unsigned int ,因此必须至少有一个 unsigned int不能表示为带符号的 int 。)

关于c - 具有有符号和无符号整数的表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26725982/

相关文章:

c - 变量未初始化

c++ - 重新排列数组元素

c - 如何强制 openMP 按特定顺序运行迭代

c - 当值可能相同时避免写入是否更快

C:有什么叫做 'prefix expression' 的东西吗?

c - 给 C 链表中的整数赋值

c - 为什么我得到这个单一输出错误?

从 C 程序调用 COBOL 程序,错误 LNKG2019 : unresolved external symbol _verkoop referenced in function _main

无法在 SQLITE、C API 中准备 INSERT 语句

c - 二叉树节点的 C 声明中的结构