假设您正在谈论标准库中的assert 宏(#defined in <assert.h>),那么您无需执行任何操作。该库已经处理了NDEBUG 标志。
如果您想让自己的代码仅在宏是 / 不是 #defined 时才执行操作,请使用 #ifdef,正如您在问题中已经怀疑的那样。
例如,我们可能有一个条件过于复杂,无法放入单个 assert 表达式中,因此我们需要一个变量。但是如果assert 扩展为空,那么我们不希望计算该值。所以我们可能会使用这样的东西。
int
questionable(const int * numbers, size_t length)
{
#ifndef NDEBUG
/* Assert that the numbers are not all the same. */
int min = INT_MAX;
int max = INT_MIN;
size_t i;
for (i = 0; i < length; ++i)
{
if (numbers[i] < min)
min = numbers[i];
if (numbers[i] > max)
max = numbers[i];
}
assert(length >= 2);
assert(max > min);
#endif
/* Now do what you're supposed to do with the numbers... */
return 0;
}
请注意,这种编码风格会使代码难以阅读,并且 要求 Heisenbugs 极难调试。更好的表达方式是使用函数。
/* 1st helper function */
static int
minimum(const int * numbers, size_t length)
{
int min = INT_MAX;
size_t i;
for (i = 0; i < length; ++i)
{
if (numbers[i] < min)
min = numbers[i];
}
return min;
}
/* 2nd helper function */
static int
maximum(const int * numbers, size_t length)
{
int max = INT_MIN;
size_t i;
for (i = 0; i < length; ++i)
{
if (numbers[i] > max)
max = numbers[i];
}
return max;
}
/* your actual function */
int
better(const int * numbers, int length)
{
/* no nasty `#ifdef`s */
assert(length >= 2);
assert(minimum(numbers, length) < maximum(numbers, length));
/* Now do what you're supposed to do with the numbers... */
return 0;
}