运行 在非调试模式下是否跳过断言?
Are assertions skipped when running in no debug mode?
我想知道当我构建我的程序并在 header 之前声明 #define NDEBUG 时,断言实际上发生了什么。
它是否在执行时跳过了代码行?或者用那个断言做点什么?
示例:
#define NDEBUG
#include<assert.h>
int main() {
int i = 5;
assert(i == 6);
return 0;
}
如果程序员做错了什么,我想在调试时查看断言,但是当我 运行 我的代码作为最终版本时,我只想跳过带有断言的行。我的意思是不要减慢程序速度。
编辑:
好的,我明白了 function-like 的宏是如何工作的。可爱
来自 2018 C 标准,7.2 1:
The header <assert.h>
defines the assert
and static_assert
macros and refers to another macro, NDEBUG
which is not defined by <assert.h>
. If NDEBUG
is defined as a macro name at the point in the source file where <assert.h>
is included, the assert macro is defined simply as:
#define assert(ignore) ((void)0)
The assert
macro is redefined according to the current state of NDEBUG
each time that <assert.h>
is included.
综上所述,如果定义了NDEBUG
,则assert
maro 将没有运行 时间效果。 (在编译期间,它确实在语法中占有一席之地;您应该在它后面跟一个分号以形成一个完整的表达式语句,然后基本上忽略它。)
我想知道当我构建我的程序并在 header 之前声明 #define NDEBUG 时,断言实际上发生了什么。
它是否在执行时跳过了代码行?或者用那个断言做点什么?
示例:
#define NDEBUG
#include<assert.h>
int main() {
int i = 5;
assert(i == 6);
return 0;
}
如果程序员做错了什么,我想在调试时查看断言,但是当我 运行 我的代码作为最终版本时,我只想跳过带有断言的行。我的意思是不要减慢程序速度。
编辑:
好的,我明白了 function-like 的宏是如何工作的。可爱
来自 2018 C 标准,7.2 1:
The header
<assert.h>
defines theassert
andstatic_assert
macros and refers to another macro,NDEBUG
which is not defined by<assert.h>
. IfNDEBUG
is defined as a macro name at the point in the source file where<assert.h>
is included, the assert macro is defined simply as:
#define assert(ignore) ((void)0)
The
assert
macro is redefined according to the current state ofNDEBUG
each time that<assert.h>
is included.
综上所述,如果定义了NDEBUG
,则assert
maro 将没有运行 时间效果。 (在编译期间,它确实在语法中占有一席之地;您应该在它后面跟一个分号以形成一个完整的表达式语句,然后基本上忽略它。)