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

前端之家收集整理的这篇文章主要介绍了为什么uint16_t在这里有所作为?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
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;

在C18中r也变为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,特别是“超大转移金额”部分.
原文链接:https://www.f2er.com/windows/371040.html

猜你在找的Windows相关文章