本文旨在用作关于C中隐式整数提升的常见问题解答,特别是由通常的算术转换和/或整数提升引起的隐式提升.
示例1)
为什么这会给出一个奇怪的大整数而不是255?
unsigned char x = 0;
unsigned char y = 1;
printf("%u\n", x - y);
Run Code Online (Sandbox Code Playgroud)
例2)
为什么这会给"-1大于0"?
unsigned int a = 1;
signed int b = -2;
if(a + b > 0)
puts("-1 is larger than 0");
Run Code Online (Sandbox Code Playgroud)
示例3)
为什么更改上例中的类型来short解决问题?
unsigned short a = 1;
signed short b = -2;
if(a + b > 0)
puts("-1 is larger than 0"); // will not print
Run Code Online (Sandbox Code Playgroud)
(这些示例适用于16位或短16位的32位或64位计算机.)
以下代码在MISRA检查中失败.具体的错误消息是:
(MISRA-C:2004 10.1/R)如果不是转换为相同签名的更宽整数类型,则整数类型表达式的值不应隐式转换为不同的基础类型.
typedef enum _MyEnum { One, Two } MyEnum;
MyEnum MyVariable;
int foo(void)
{
int result = 1;
if (One == MyVariable) // fails here with MISRA-C:2004 10.1/R
{
result = 2;
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
One和MyVariable?编辑:编译器是TI"MSP430 C/C++编译器v4.0.0",包含MISRA规则检查.
首先,这类似于:如何隐式转换整数类型?但是有一个不同的MISRA警告.
编译器不会生成MISRA错误,但静态分析工具会生成错误.我有一张正在进行工具制造商的票.
鉴于:
#include <stdio.h>
enum Color {RED, VIOLET, BLUE, GREEN, YELLOW, ORANGE};
int main(void)
{
enum Color my_color;
my_color = BLUE;
if (my_color == YELLOW) // Generates MISRA violation, see below.
{
printf("Color is yellow.\n");
}
else
{
printf("Color is not yellow.\n");
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
静态分析工具正在为if语句生成MISRA违规:
MISRA-2004 Rule 10.1 violation: implicitly changing the signedness of an expression.
Converting "4", with underlying type "char" (8 bits, signed),
to type "unsigned int" (32 bits, unsigned) with …Run Code Online (Sandbox Code Playgroud)