主要内容

MISRA C:2023 Rule 10.5

R2026b

The value of an expression should not be cast to an inappropriate essential type

自 R2024a 起

描述

The value of an expression should not be cast to an inappropriate essential type 1 .

理由

变量类型之间的转换

 源类型
布尔 字符 枚举 有符号 无符号 实数浮点 复数浮点
目标类型 布尔  避免避免避免避免避免避免
字符 避免    避免避免
枚举 避免避免避免避免避免避免避免
有符号 避免      
无符号 避免      
实数浮点 避免避免     
复数浮点 避免避免     

一些不适当的显式强制转换包括:

  • 在 C99 中,将赋值强制转换为 _Bool 的结果始终为 0 或 1。当强制转换为另一种被定义为本质布尔类型的类型时,结果则不一定如此。

  • 强制转换为基本枚举类型可能会产生一个不在该类型的枚举常量集内的值。

  • 从基本布尔类型强制转换为任何其他类型不太可能有意义。

  • 在浮点类型和字符类型之间转换没有意义,因为两种表示之间没有精确的映射。

一些可接受的显式强制转换包括:

  • 更改执行后续算术运算时所使用的类型。

  • 故意截断一个值。

  • 为了确保清晰度而进行显式类型转换。

有关本质类型的详细信息,请参阅Essential Type Model Used in MISRA C Rule Checking。

故障排除

如果您预期会出现违规,但未看到该违规,请参阅诊断为何编码规范违规未按预期显示。

示例

全部展开

此示例展示了在适当的本质类型之间进行的合规强制转换,以及在不适当的类型之间进行的不合规强制转换。

#include <stdbool.h>
#include <stdint.h>

enum vehicleType { CAR, TRUCK, MOTORCYCLE } vehicle;
enum colorType { RED, BLUE, GREEN } color;

void validateCasting() {
    ( int32_t ) 3U;       /*  Compliant */
    ( bool ) false;       /*  Compliant - 'false' from stdbool.h is essentially Boolean */
    ( bool ) 0;           /*  Compliant - by exception */
    ( bool ) 3U;          /* Noncompliant */

    ( int32_t ) vehicle;  /*  Compliant */
    ( enum vehicleType ) 3; /* Noncompliant */
    ( char ) color;       /*  Compliant */
}

检查信息

组:基本类型模型
类别:建议
AGC 类别:建议
PQL 名称:std.misra_c_2023.R10_5

版本历史记录

在 R2024a 中推出

全部展开


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:2025

  • MISRA C++:2008

  • MISRA C++:2023

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