メインコンテンツ

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

Bitwise operators shall only be applied to operands of unsigned underlying type.

説明

ルール定義

Bitwise operators shall only be applied to operands of unsigned underlying type. 1

根拠

ビット演算を符号付きオペランドに適用しても意味がありません。ビット演算を符号付きオペランドに適用すると、想定外かつ実装に依存する結果となる可能性があります。たとえば、負の数値を右シフトする場合、環境によって異なる結果になります。符号付きオペランドに対するビット演算の使用は避けてください。

Polyspace 実装

Polyspace® は、符号付きオペランドまたは式にビット演算が適用された場合に、このルールの違反を報告します。

トラブルシューティング

ルール違反が想定されるものの、Polyspace から報告されない場合は、コーディング規約違反が想定どおりに表示されない理由の診断を参照してください。

すべて展開する

typedef signed   short        int16_t;
typedef unsigned short        uint16_t;

void foo(uint16_t ua, uint16_t ub, int16_t a)
{
	if   (   ( ua & a ) == 0x1234U ) {}        // Noncompliant
	if   (   ( ua | ub ) == 0x1234U ) {}       // Compliant
	if   (   ~a == 0x1234U ) {}                // Noncompliant
	if   (   ~ua == 0x1234U ) {}               // Compliant
}

この例では、Polyspace が、符号付きオペランド a に対するビット演算の使用にフラグを設定します。uaub、および 16 進数 0x1234U などの符号なしオペランドを使用するビット演算は、このルールに準拠しています。

チェック情報

グループ: Expressions
カテゴリ: 必要

バージョン履歴

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.