主要内容

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

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

An implicit integral conversion shall not change the signedness of the underlying type

描述

规则定义

An implicit integral conversion shall not change the signedness of the underlying type. 1

理由

一些从有符号数据类型到无符号数据类型的转换可能会导致实现定义的行为。您可能会看到转换导致的意外结果。

Polyspace 实现

检查项会标记从有符号整数数据类型到无符号整数数据类型的隐式转换,或者从无符号整数数据类型到有符号整数数据类型的隐式转换。

检查项假定 ptrdiff_t 是一个有符号整数。

报告中的补充消息

隐式整数转换不应更改基础类型的符号性。

二进制 + 操作数之一的隐式转换,其基础类型为 typename_1typename_2

故障排除

如果您预计存在违规,而 Polyspace® 未报告该违规,请参阅Diagnose Why Coding Standard Violations Do Not Appear as Expected

示例

全部展开

typedef char int8_t;
typedef unsigned char uint8_t;

void func()
  {
    int8_t s8;
    uint8_t u8;

    s8 = u8; //Noncompliant
    u8 = s8 + u8; //Noncompliant
    u8 = static_cast< uint8_t > ( s8 ) + u8; //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.