tags:

views:

56

answers:

3

From assert.h file in C:

#define assert(expr)     (__ASSERT_VOID_CAST (0))

I wonder what is (__ASSERT_VOID_CAST (0))? I try to find its implementation but could not find anywhere.

A: 

From assert.h, a few lines above the definition of assert (linux, kubuntu):

#if defined __cplusplus && __GNUC_PREREQ (2,95)
# define __ASSERT_VOID_CAST static_cast<void>
#else
# define __ASSERT_VOID_CAST (void)
#endif
sth
+3  A: 

Well, __ASSERT_VOID_CAST will be another macro somewhere, and when asserts are 'tuned off' it will expand to something equivalent with

((void) 0)

which is a way to get a void expression. In older implementations assert() just expanded to an empty string, but a void-expression will let you use the comma-operator to do wriggle it into an expression, like:

while(assert(n > 0), k/n > 10) { ... }
Henk Holterman
Wouldn't a simple 0, without the void cast, work as well there?
Thomas Padron-McCarthy
A simple `0;` gives 'warning: statement with no effect' when used as a statement. So it might work for the `while` fragment, it won't do for the more common use of `assert()` as a statement.
Pete Kirkham
@Thomas - yes it would. but remember that the `assert()` macro is defined as being a void expression. So having it expand to a simple `0` would be incorrect.
Michael Burr
+2  A: 

In the assert.h on my particular system it says:

#if defined __cplusplus && __GNUC_PREREQ (2,95)
# define __ASSERT_VOID_CAST static_cast<void>
#else
# define __ASSERT_VOID_CAST (void)
#endif

So it's a cast to void, and the reason to use it is to avoid warnings about unsed values when NDEBUG is set to true.

Thomas Padron-McCarthy