c - 表达式是什么,真还是假

标签 c

uint8_t ui8 = 255;
ui8 == (int16_t)-1

据我了解standard :

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.

ui8 将被转换/提升为 int16_t,然后它的算术值将是 -1。不幸的是,我使用的编译器说我不对。

最佳答案

每当 uint8_t 或任何其他小整数类型用作表达式的一部分时,它都会被提升为 int 类型的整数。 int16_t 也是如此,以防 int 大于 16 位。

因此您的代码保证等于:

(int)255 == (int)-1

这总是错误的。

由于整数提升,两个操作数已经是同一类型,因此操作数之间不会发生平衡。

关于c - 表达式是什么,真还是假,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32310936/

相关文章:

c - 限制C中一个文件内全局变量的范围

c - 为什么我不能用C代码制作这个系列?

无法对齐 "pointer targets signedness"

c++ - 如何分析对函数的每次调用?

函数之间的 C 字符串作用域

c - 取消引用未定义的指针值?

C - 按值传递结构+成员

c - 进程返回 -1 (0xFFFFFFFF)

c - 初始化器不是常量。马洛克

c - 复制字符串缓冲区时出现段错误