主要内容

本页采用了机器翻译。点击此处可查看最新英文版本。

MISRA C++:2008 Rule 5-0-5

There shall be no implicit floating-integral conversions

描述

规则定义

There shall be no implicit floating-integral conversions. 1

理由

如果从浮点类型转换为整数类型,则会丢失信息。除非您显式地将浮点型转换为整数型,否则无法确定信息丢失是否是故意的。此外,如果浮点值无法用整数类型表示,则行为未定义。

从整数转换为浮点类型可能会导致值的表示不精确。转换过程中产生的误差可能会在后续运算中累积,并导致意外结果。

Polyspace 实现

检查项标记浮点类型(floatdouble)与整数类型(shortint 等)之间的隐式转换。

本规则优先于 5-0-4 和 5-0-6,若两者同时适用。

故障排除

如果您预期会出现违规,而 Polyspace® 未报告该违规,请参阅诊断为何编码规范违规未按预期显示

示例

全部展开

typedef signed int int32_t;
typedef float float32_t;

void func ( )
  {
    float32_t f32;
    int32_t   s32;
    s32 = f32;   //Noncompliant
    f32 = s32;   //Noncompliant
    f32 = static_cast< float32_t > ( s32 ); //Compliant
  }

在此示例中,当浮点类型被隐式转换为整数类型时,规则被违反。如果转换是显式的,则不会发生违规。

检查信息

组:表达式
类别:必需

版本历史记录

在 R2013b 中推出


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.