メインコンテンツ

MISRA C:2023 Rule 23.4

A generic association shall list an appropriate type

R2024a 以降

説明

ルール定義

A generic association shall list an appropriate type 1 .

根拠

総称選択の制御式では、型と関連リストの型名を比較する前に、lvalue 変換が行われます。この lvalue 変換では、次の処理が行われます。

  • constvolatileatomic などの最上位の修飾子を削除する

  • 関数と配列をポインターに変換する

関連リストに修飾子付きの型、配列、または関数の型が含まれている場合、制御式が関連リストに一致することはありません。次のコードについて考えます。

typedef const uint32_t const_int;

#define get_type_id_of(X) _Generic((X), const_int : 0, int : 1)

const_int x = 7;
get_type_id_of(x);
lvalue 変換の後で x の型が int と一致するので、マクロ get_type_id_of(x)1 と評価されます。この動作を回避するには、関連リストにある適切な型を使用します。

名前のない struct または union はすべて個別の型なので、関連リストの名前のない struct または union を使用することは、このルールに違反します。制御式の名前のない struct は、関連リストの名前のない struct とは一致しません。一方、制御式の名前のない struct は、既定の関連とは一致します。

Polyspace 実装

総称選択の関連リストに次のいずれも含まれていない場合には、ルール チェッカーは違反を報告します。

  • const 修飾子付きの型

  • volatile 修飾子付きの型

  • atomic

  • 配列または関数の型

  • 名前のない型

トラブルシューティング

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

すべて展開する

この例では、総称選択ステートメントの関連リストで、修飾子付きの型や配列などの不適切な型が使用されています。ルール チェッカーは違反を報告します。


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

/*
 * Array type is not allowed in type selection
 */
typedef uint8_t a_byte_array[256];
#define is_a_byte_array(X) _Generic((X), a_byte_array : true, default : false) /*Noncompliant*/
void non_compliant_with_arrays() {
	a_byte_array some_bytes;
	(void) is_a_byte_array(some_bytes);
}


/*
 * Function type is not allowed in type selection
 */
typedef void a_function(void);
extern void f(void);

/*
 * Qualified types are non-compliant in type selection
 */
typedef const uint32_t const_int;
typedef volatile uint32_t volatile_int;
typedef const volatile uint32_t const_volatile_int;
typedef _Atomic uint32_t atomic_int;

#define is_const_type(X) _Generic((X), const_int : true, default: false)       /*Noncompliant*/
#define is_volatile_type(X) _Generic((X), volatile_int : true, default: false) /*Noncompliant*/
#define is_atomic_type(X) _Generic((X), atomic_int : true, default : false)    /*Noncompliant*/

#define get_type_id_of(X) _Generic((X)                                         /*Noncompliant*/ \
                                   , const_int : 0 \
                                   , volatile_int : 1 \
                                   , const_volatile_int : 2 \
                                   , atomic_int : 3)

void non_compliant_with_qualifiers() {
	const_int x = 7;
	(void) is_const_type(x);
	(void) is_volatile_type(x);
	(void) is_atomic_type(x);
	(void) get_type_id_of(x);
}

チェック情報

グループ: 総称選択
カテゴリ: 必要
AGC カテゴリ: 必要

バージョン履歴

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++:2008

  • MISRA C++:2023

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