yohhoyの日記

技術的メモをしていきたい日記

NEO assertマクロ

プログラミング言語C/C++の次期標準規格C2x(C23)およびC++2c(C++26)では、アサーションマクロassertの改善が行われる。

#include <assert.h> // C/C++
#include <cassert>  // C++のみ

int is_valid(int);

assert( "42 shall be vaild", is_valid(42) );
// NG: C17/C++20現在
// OK: C2x/C++2c以降

assert(("42 shall be vaild", is_valid(42)));
// OK: 式全体を括弧で囲う

C言語ではトラブルを引き起こすケースは少ないが*1C++言語では初期化子リストやテンプレートパラメータなどでトラブル発生頻度が高い。はず。

// C++事例
assert( get_vec() == std::vector{1, 2, 3} );
assert( calc_mul<int,2>(3) == 6 );

本件は遡及適用されるバグ修正ではなく、新機能として取り扱われる模様。JTC1/SC22/WG14 2022年1-2月会議録*2より引用:

5.29 Sommerlad, Make assert() macro user friendly for C and C++ v2 [N 2829]
Discussion of how the current wording says "scalar expression" so this could be seen as a bug fix.

Concerns about making this a special macro definition vs all the other macros in the standard. Makes it inconsistent. Counters included incremental improvement or that this was the only macro that is a problem (author mentioned specifically for C++).

関連URL

*1:本文中にあるカンマ演算子を用いた作為的な例も、実用的には論理積演算子(&&)を用いて代替記述できる。

*2:https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2991.pdf