这个no-op while-loop用于assert宏的原因是什么?

这个no-op while-loop用于assert宏的原因是什么?

问题描述:

我正在查看一个代码库,其中 assert 宏在非调试配置中扩展为这样:

I'm reviewing a codebase where assert macro is expanded like this in non-debug configurations:

#define assert( what ) while( 0 )( ( void )1 )


$ b b

我不太明白。显然目标是有一个无操作。

which I don't quite get. Obviously the goal is to have a no-op. Then why not expand into an empty string?

#define assert( what )

最有可能避免编译器警告。检查此代码是否引发有关空语句的警告:

Most likely to avoid compiler warnings. Check whether this code provokes a warning about an empty statement:

if (foo);

如果是这样,那么你想在发布模式下使用相同的警告吗? p>

If it does, then do you want the same warning in release mode for the following code?

if (foo) assert(what);

C99(与C ++ 11相关)还说, assert 将展开为一个void表达式。 IIRC,单独的空格不是表达式,即使后面跟着分号的空格是表达式语句。良好的旧BNF语法。

C99 (which is relevant to C++11) also says that assert expands "to a void expression". IIRC, whitespace alone isn't an expression, even though whitespace followed by a semi-colon is an expression-statement. Good old BNF grammar.

顺便说一下, assert 的定义不符合标准。 C89和C99都说当定义 NDEBUG 时,assert定义为:

By the way, this definition of assert is not standard-conforming. C89 and C99 both say that when NDEBUG is defined, then assert is defined as:

#define assert(ignore) ((void)0)



作者认为这是一个重要的要求,但是一个程序可以例如将宏扩展字符串化并期待一个特定的结果。

I'm not sure whether the authors consider it an important requirement, but a program could for example stringify the macro expansion and expect a particular result.