问题描述
在下面的 C 代码中,在检查 if 条件时,我收到 Misra 警告
The operand of the opeartor '=='do not have same essential type category: one is 'Boolean' and other is 'unsigned'
在头文件 file1.h
#define timer_4sec (uint8)160
#define bool_rolltime (roll_time_count < timer_4sec)
在源文件中,file1.c
static uint8 roll_time_count = timer_4sec
void function()
{
if(bool_rolltime == True)
{
printf("rolling ..\n");
}
}
void function2()
{
//update the roll_time_count status,increment and decrement static timer variable.
}
问题就在这里if(bool_rolltime == True)
。我知道 roll_time_count
和 timer_4sec
是 uint8
变量。所以我试图像这样解决这个警告
#define bool_rolltime (bool)(roll_time_count < timer_4sec)
此代码是否是避免 Misra 错误的正确方法?如果不是,请建议如何避免此类警告?
解决方法
这与您昨天提出的问题基本相同。正如我当时回答的那样,您需要告诉静态分析器哪些类型是布尔值。例如 bool
、false
和 true
。我不知道你为什么使用一些自制的标准 True
,但正如你所注意到的,这不是一个好主意。同样,放弃自制 uint8
并使用标准 C uint8_t
。
此外,由于隐藏简单表达式的臭宏,您会违反 MISRA。这是一种糟糕的做法,无论是 MISRA 还是没有 MISRA。你不应该发明一些神秘的宏语言。保持简单易读:
#define timer_4sec 160u // no need for cast but you need the u suffix for MISRA-C
static uint8_t roll_time_count = timer_4sec;
void function (void) // empty parenthesis is obsolete C,write (void)
{
if(roll_time_count < timer_4sec)
{
printf("rolling ..\n");
}
}
既然我们保持代码简单易读,它也自动变成了 MISRA-C 兼容。由于带有“u”后缀,<
的两个操作数都属于相同的“无符号”基本类型类别。
同样,就像我昨天已经回答的那样,您需要研究 MISRA-C 指南中的基本类型规则,否则您将无法理解该工具不断告诉您的内容。