volatile uint16_t r;
unsigned char poly = 0x07;
unsigned char c = 0;
r = (c << 8) ^ poly;
当代码在 Linux 上用 gcc 编译时,r
是 7
。
当同样的代码被Microchip C18编译时,r
为0
。
为什么?
如果我把它改成:
volatile uint16_t r;
uint16_t poly = 0x07;
uint16_t c = 0;
r = (c << 8) ^ poly;
r
在 C18 中也变成了 7
。
C18手册中有关于整数提升的章节,但我认为这与我的问题无关。无论如何,它在这里:
ISO mandates that all arithmetic be performed at int precision or greater. By default, MPLAB C18 will perform arithmetic at the size of the largest operand, even if both operands are smaller than an int. The ISO mandated behavior can be instated via the -Oi command-line option.
最佳答案
自 c << 8
在此编译器中未定义,无法预测 xor 的结果。结果可以是编译器选择的任何内容。
参见 What Every C Programmer Should Know About Undefined Behavior有关未定义行为的介绍,尤其是“超大转移量”部分。
关于c - 为什么 uint16_t 在这里有所作为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6091647/