32

I am using VC++. Is assert(false) ignored in release mode?

jww
  • 97,681
  • 90
  • 411
  • 885
Brian R. Bondy
  • 339,232
  • 124
  • 596
  • 636

6 Answers6

32

If compiling in release mode includes defining NDEBUG, then yes.

See assert (CRT)

bejado
  • 1,430
  • 12
  • 19
activout.se
  • 6,058
  • 4
  • 27
  • 37
  • 2
    The documentations states "The assert routine is available in both the release and debug versions of the C run-time libraries." Looking at the assert.h header though, it's certainly true that defining NDEBUG before including it will cause assert() to compile to a no-op. However, it is entirely possible for release mode code that does not define NDEBUG to cause an assertion to abort. I just wanted to clarify my own understanding and share what I found. – Joe Bane Oct 05 '12 at 14:52
8

IIRC, assert(x) is a macro that evaluates to nothing when NDEBUG is defined, which is the standard for Release builds in Visual Studio.

Harper Shelby
  • 16,475
  • 2
  • 44
  • 51
6

The assert macro (at least it is typically a macro) is usually defined to no-op in release code. It will only trigger in debug code. Having said that. I have worked at places which defined their own assert macro, and it triggered in both debug and release mode.

I was taught to use asserts for condition which can "never" be false, such as the pre-conditions for a function.

grieve
  • 13,220
  • 10
  • 49
  • 61
2

Only if NDEBUG is defined I think (which it will be by default for Visual C++ apps).

Rob
  • 76,700
  • 56
  • 158
  • 197
1

I think it is a mistake to rely too much on the exact behavior of the assert. The correct semantics of "assert(expr)" are:

  • The expression expr may or may not be evaluated.
  • If expr is true, execution continues normally.
  • If expr is false, what happens is undefined.

More at http://nedbatchelder.com/text/assert.html

Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
  • 1
    The correct semantics is described in ISO C. If assertions are enabled (`NDEBUG` is not defined prior to including ``) then if the controlling expression of an `assert` compares equal to zero, then the text of the expression, the file and line number are printed in some implementation-defined message on the standard error stream. Then the `abort` function is called. (As of C99, the message is required to include the function name also.) – Kaz Oct 07 '12 at 03:45
  • When creating performance code, building without asserts can be important to get right in a release build. – William J Bagshaw Mar 29 '22 at 06:46
1

same for GNU :

  #ifdef    NDEBUG

  # define assert(expr)     (__ASSERT_VOID_CAST (0))
Matt
  • 74,352
  • 26
  • 153
  • 180
RzR
  • 3,068
  • 29
  • 26