Belloc
Belloc

Reputation: 6390

Why the definition of the assert macro, in a release build, cannot be just `#define assert(expression) 0`?

This is the definition of the assert macro in Visual Studio 2019

#ifdef NDEBUG

    #define assert(expression) ((void)0)

#else

    _ACRTIMP void __cdecl _wassert(
        _In_z_ wchar_t const* _Message,
        _In_z_ wchar_t const* _File,
        _In_   unsigned       _Line
        );

    #define assert(expression) (void)(                                                       \
            (!!(expression)) ||                                                              \
            (_wassert(_CRT_WIDE(#expression), _CRT_WIDE(__FILE__), (unsigned)(__LINE__)), 0) \
        )

#endif

As you can see above, the definition of the macro assert in a release build is

#define assert(expression) ((void)0)

Why can't it be just #define assert(expression) 0 ?

Upvotes: 3

Views: 239

Answers (2)

jamesdlin
jamesdlin

Reputation: 90015

Some compilers might want the (void) cast to suppress warnings about an expression whose value isn't used.

Upvotes: 2

Julien Thierry
Julien Thierry

Reputation: 661

This prevents using assert as an expression. So if one does (by mistake):

a = assert(something);

The compiler will throw an error both for a release and debug build.

Upvotes: 3

Related Questions