c - 为什么 uint16_t 在这里有所作为?

标签 c integer microcontroller pic

volatile uint16_t r;
unsigned char poly = 0x07;
unsigned char c = 0;

r = (c << 8) ^ poly;

当代码在 Linux 上用 gcc 编译时,r7
当同样的代码被Microchip C18编译时,r0
为什么?

如果我把它改成:

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/

相关文章:

java - 如何将 ArrayList 中的元素更改为不同的对象类型?

c - 使用DS1620 IC和arm微 Controller 的温度计

我可以正确地比较 avx 中的零寄存器吗?

c++ - 初始化 C/C++ 多维数组时忽略大小

string - "set foo to text returned of"代表数字吗?

embedded - 在 20Mhz 瑞萨微 Controller IO 引脚上驱动高频输出(32Khz)

c - 我怎样才能在微 Controller 中捕获意外重置

c - XDeleteProperty 返回 BadRequest 错误

c - 使用带有 createThread(...) 的 HANDLE(void*) 的动态数组

c++ - 如何在 C++ 中将纬度的小数部分存储到 4 个无符号字符中