简体   繁体   English

如果表达式为布尔类型,则使用Misra-C 2012规则10.1布尔操作数

[英]Misra-C 2012 rule 10.1 boolean operand to be used in case where expression is of boolean type

The following lines generate misra violations. 以下几行产生违反misra的行为。

unsigned int u16_a;
unsigned char u8_b;  
if (u16_a && u8_b) // Generates Misra-C 10.1 violation. 
(u16_a) ? 2 : 1 //Generates Misra-C 10.1 violation.

The violation says the operand is of essential signed type but should be of boolean type. 违反规定操作数是必需的带符号类型,但应为布尔类型。

For the 1st violation, If I type cast them to _Bool type, will it not result in overflow since I remember size of bool datatype is 1 byte. 对于第一次违反,如果我将类型强制转换为_Bool类型,则不会导致溢出,因为我记得bool数据类型的大小为1个字节。

For the 2nd violation tried this: 对于第二次违规,请尝试以下操作:

(u16_a == 0)? 1 :2 // does this work

I'm pretty new in dealing MISRA violations and confused with most of the violations. 我在处理MISRA违规方面还很新,并且与大多数违规混为一谈。 Thanks, in advance. 提前致谢。

Basically, MISRA-C wants us to treat logical/relational operators as if they returned a bool type (like in C++) and generally "pretend" that C has a distinct bool type that is separate from integers. 基本上,MISRA-C希望我们将逻辑/关系运算符视为返回布尔类型(就像在C ++中一样),并且通常“假装” C具有与整数分开的独特布尔类型。 This gives increased type safety when you use static analysis tools. 使用静态分析工具时,这可以提高类型安全性。

Which means that you have to be explicit with checks against zero: 这意味着您必须明确检查零:

if ( (u16_a!=0u) && (u8_b!=0u) )

and

(u16_a!=0) ? 2u : 1u

Or preferably something more readable: 或者最好是更易读的东西:

bool b_a = u16_a!=0u;
bool b_b = u8_b!=0u;

if(b_a && b_b) // MISRA compliant, operands are essentially boolean types

Use if ( (u16_a !=0u) && (u8_b != 0u) ) instead of if (u16_a && u8_b) for the first example. 在第一个示例中使用if ( (u16_a !=0u) && (u8_b != 0u) )代替if (u16_a && u8_b)

For the latter: (u16_a == 0)? 1 :2 对于后者: (u16_a == 0)? 1 :2 (u16_a == 0)? 1 :2 seems to be ok to me. (u16_a == 0)? 1 :2对我来说似乎还可以。

Bottom line is that the whole point of this MISRA requirement is: "specify explicitly when comparing against a value, instead of relying on the defaults". 最重要的是,此MISRA要求的重点是:“在与值进行比较时明确指定,而不要依赖默认值”。

The C standard says: C标准说:

6.3.1.2 Boolean type 6.3.1.2布尔类型

1 When any scalar value is converted to _Bool, the result is 0 if the value compares equal to 0; 1当任何标量值转换为_Bool时,如果该值比较等于0,则结果为0;否则,结果为0。 otherwise, the result is 1. 否则,结果为1。

So casting to _Bool does the right thing. 因此,强制转换为_Bool是正确的事情。 (x != 0) may be more readable than ((_Bool)x) though. (x != 0)可能比((_Bool)x)更具可读性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM