主要内容

本页翻译不是最新的。点击此处可查看最新英文版本。

MISRA C:2012 Rule 14.4

The controlling expression of an if statement and the controlling expression of an iteration-statement shall have essentially Boolean type

描述

规则定义

The controlling expression of an if statement and the controlling expression of an iteration-statement shall have essentially Boolean type 1

理由

强定型要求 if 语句或迭代语句的控制表达式本质上应为布尔类型。

Polyspace 实现

Polyspace® 不会标记整数常量,例如 if(2)

分析会识别布尔类型,bool_Bool(在 stdbool.h 中定义)

您还可以使用有效布尔类型 (-boolean-types) 选项定义本质上为布尔的类型。

故障排除

如果您预计存在违规,但未看到该违规,请参阅Diagnose Why Coding Standard Violations Do Not Appear as Expected

示例

全部展开

#include <stdbool.h>
#include <stdlib.h>

#define TRUE 1

typedef _Bool bool_t;
extern bool_t flag;

void foo(void){
    int *p = 1;
    int *q = 0;
    int i = 0;
    while(p){}           /* Non-compliant - p is a pointer */

    while(q != NULL){}   /* Compliant */

    while(TRUE){}        /* Compliant */

    while(flag){}        /* Compliant */

    if(i){}              /* Non-compliant - int32_t is not boolean */

    if(i != 0){}         /* Compliant */

    for(int i=-10; i;i++){}   /* Non-compliant - int32_t is not boolean */

    for(int i=0; i<10;i++){}  /* Compliant */
}

此示例显示了 whileiffor 语句中的各种控制表达式。

不合规语句(第一个 whileiffor 示例)使用单个非布尔变量。如果使用单个变量作为控制语句,该变量必须本质上为是布尔值(第 17 行和第 19 行)。布尔表达式也符合 MISRA™。

检查信息

组:控制语句表达式
类别:必需
AGC 类别:建议

1 All MISRA coding rules and directives are © Copyright The MISRA Consortium Limited 2021.

The MISRA coding standards referenced in the Polyspace Bug Finder™ documentation are from the following MISRA standards:

  • MISRA C:2004

  • MISRA C:2012

  • MISRA C:2023

  • MISRA C++:2008

  • MISRA C++:2023

MISRA and MISRA C are registered trademarks of The MISRA Consortium Limited 2021.