代码之家  ›  专栏  ›  技术社区  ›  Hariom Singh

MISRA C:2012规则14.4

  •  2
  • Hariom Singh  · 技术社区  · 6 年前

    根据米斯拉规则 if语句的控制表达式和迭代语句的控制表达式基本上应为布尔型

    #include <stdbool.h>
    #include <stdlib.h>
    
    void foo(void){
        int i = 0;
    
        if(i){}              /* Non-compliant - int32_t is not boolean */
    
        if(i != 0){}         /* Compliant */
    
    }
    

    任何见解都会有帮助

    4 回复  |  直到 6 年前
        1
  •  10
  •   Lundin    6 年前

    基本原理与规则一起提供:强类型。控制表达式本质上应该是布尔类型。等式、关系等运算符的结果本质上是布尔的,而在 int 或不带运算符的指针表示表达式是所使用的类型。

    (作为一个侧重点,这可能与C++的兼容性非常重要,在那里,许多操作符实际上返回了一个 bool operator 函数返回 布尔 .)

    if(ptr != NULL) 只能是指针与NULL的比较。没有误解的余地。 if(ptr) 可能是与NULL的比较,也可能是一个意外的手指滑动,程序员实际上是指 if(*ptr) . 另外,如果指针有一个神秘的名字,它是什么并不明显 if(xyz) 是的,但很明显什么 if(xyz != NULL) 是。

    if(func) 哪里 if(func()) 是有意的。请记住,许多MISRA规则都是为了静态分析器的利益而存在的。


    #include <stdio.h>
    #include <stdbool.h>
    
    int main (void)
    {
      int x = false;
      x = ~x;
    
      if(x)
      {
        puts("x is true");
        if(x!=true)
        {
          puts("but x is not true\n");
        }
      }
    
      bool y = x;
    
      if(y)
      {
        puts("y is true");
        if(y==true)
        {
          puts("I swear, y is really true");
        }
      }
    }
    

    输出:

    x is true
    but x is not true
    
    y is true
    I swear, y is really true
    
        2
  •  4
  •   Andrew    6 年前

    “MISRA-C引入了一个强大的类型模型,以帮助用户避免在C类型模型中出现意外问题。 " stated in the MISRA forum, as an "official" MISRA C WG answer

    在if语句中只使用整数怎么会导致问题呢?

        3
  •  1
  •   Paul Ogilvie    6 年前

    我想不出什么特别的原因。

    d 事情可能会出错,但double的计算结果将是/不是0.0,因此仍然是if或iteration语句的有效表达式。或者一个指向字符(字符串)的指针,但在那里它也会产生一个有效的表达式。

    所以我能想到的唯一原因是,现在很明显它是一个布尔表达式,即更好的可读性。

    char *s;
    if (s != NULL && *s != '\0')
    

    也可以写成:

    if (s != 0 && *s != 0)
    

    d :

    if (d != 0.0)
    
        4
  •  1
  •   Andrew Henle    6 年前

    #include <stdbool.h>
    #include <stdlib.h>
    
    void foo(void){
        int i = 0;
    
        if(i){}              /* Non-compliant - int32_t is not boolean */
    
        if(i |= 0){}         /* Non-compliant - type is still int32_t */
    
    } 
    

    或者更明显的

    #include <stdbool.h>
    #include <stdlib.h>
    
    void foo(void){
        int i = 0;
    
        if(i){}              /* Non-compliant - int32_t is not boolean */
    
        if(i = 0){}         /* Non-compliant */
    
    }
    
    推荐文章