メインコンテンツ

MISRA C:2012 Rule 20.4

A macro shall not be defined with the same name as a keyword

説明

ルール定義

A macro shall not be defined with the same name as a keyword 1 .

根拠

キーワードの意味を変更するのにマクロを使用すると紛らわしくなる可能性があります。キーワードと同じ名前でマクロが定義されている状態で標準ヘッダーをインクルードする場合、動作は未定義です。

レポート内の追加のメッセージ

  • The macro macro_name shall not be redefined.

  • The macro macro_name shall not be undefined.

トラブルシューティング

ルール違反を想定していてもその違反が表示されない場合、コーディング規約違反が想定どおりに表示されない理由の診断を参照します。

すべて展開する

#include <stdlib.h>
#define int some_other_type /* Non-compliant - int keyword behavior altered */
           
//...

この例では、#defineint キーワードの動作を変更するため、ルール 20.4 に違反します。標準ヘッダーをインクルードすると未定義の動作になります。

修正 — キーワードの名前を変更

1 つの修正方法として、別のキーワードを使用します。

#include <stdlib.h>
#define int_mine some_other_type

//...
#define while(E) for ( ; (E) ; )  /* Non-compliant - while redefined*/
#define unless(E) if ( !(E) )     /* Compliant*/

#define seq(S1, S2) do{ S1; S2;} while(false)  /* Compliant*/
#define compound(S) {S;}                       /* Compliant*/
//...

この例では、キーワード while を再定義するのは準拠しませんが、ステートメントに展開するマクロの定義は準拠します。

#define inline // Non-compliant 

この例では、inline の再定義は C90 に準拠していますが、inline は C90 のキーワードではないので C99 に準拠していません。

チェック情報

グループ: プリプロセッサ命令
カテゴリ: 必要
AGC カテゴリ: 必要

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.