MISRA C 2012 是否表示不使用 bool

Does MISRA C 2012 say not to use bool

我正处于为新项目设计框架的早期阶段。

我定义了一个 return 类型为 "bool"

的函数

我从 PC-Lint

得到了这个输出
    Including file sockets.h (hdr)
bool sock_close(uint8_t socket_id);
^
"LINT: sockets.h (52, 1) Note 970: Use of modifier or type '_Bool' outside of a typedef [MISRA 2012 Directive 4.6, advisory]"

我继续在另一个 header 中定义它以关闭 lint:

typedef bool bool_t;

然后我开始想知道为什么我必须这样做以及为什么它改变了一切。我转向 MISRA 2012 Dir 4.6。它主要关注基本类型(如 short、int 和 long)的宽度、它们的宽度以及它们的签名方式。

标准没有给出布尔值的任何放大、有理、异常或示例。

bool 在 C99 的 stdbool.h 中明确定义为 _Bool。那么这个标准真的适用于 bool 吗?

根据 C99 的第 6.2.5 节,我认为 _Bool 明确始终是 "smallest standard unsigned integer type large enough to store the values 0 and 1"。所以我们知道 bool 是无符号的。 _Bool 不是固定宽度并且主题以某种方式被提升的事实只是一个问题吗?因为理性似乎与这个概念相矛盾。

Adherence to this guideline does not guarantee portability because the size of the int type may determine whether or not an expression is subject to integer promotion.

仅仅放置 typedef bool bool_t; 如何改变任何东西 - 因为我没有做任何事情来指示这样做的宽度或签名? bool_t 的宽度也将仅取决于平台。有没有更好的方法来重新定义bool?

A type must not be defined with a specific length unless the implemented type is actually of that length

所以typedef bool bool8_t;应该是完全非法的。

Gimpel 对指令 4.6 的解释是错误的还是他们正确?

Use of modifier or type '_Bool' outside of a typedef [MISRA 2012 Directive 4.6, advisory]

废话,指令4.6只关心使用stdint.h中的类型而不是intshort等。指令是关于基本数值类型bool 与该指令无关,因为它不是数字类型。

出于未知原因,MISRA-C:2012 示例使用了一种名为 bool_t 的奇怪类型,这不是标准类型。但是 MISRA 绝不强制在任何地方使用这种类型,特别是他们在指令 4.6 中不强制执行它,它甚至没有提到布尔值。 MISRA 不反对在任何地方使用 bool_Bool

Is Gimpel wrong in their interpretation of Directive 4.6

是的,他们的工具给出了错误的诊断。

此外,您可能必须配置该工具(如果可能)以告知它使用的是哪种 bool 类型。 5.3.2 提到如果不使用 _Bool 可能必须这样做,暗示所有静态分析器都必须理解 _Bool。但是即使bool类型配置正确,dir 4.6也没有任何关系

布尔类型的一个潜在问题是,C99 之前的许多代码使用单字节类型来保存 true/false 值,其中相当一部分可能使用名称 "bool".尝试将 256 的任何倍数存储到大多数此类类型中将被视为存储零,而将 256 的非零倍数存储到 c99 "bool" 中将产生 1。如果一段代码使用 C99 "bool" 被移植到一段使用 typedef 字节的代码中,生成的代码很容易出现故障(为 typedef 字节编写的代码不太可能在存储其他值时依赖任何特定行为比 0 或 1)。