Why is (void) 0 a no operation in C and C++?

前端 未结 5 2134
情歌与酒
情歌与酒 2020-12-04 11:10

I have seen debug printfs in glibc which internally is defined as (void) 0, if NDEBUG is defined. Likewise the __noop for Visual C++ compiler

5条回答
  •  心在旅途
    2020-12-04 11:20

    I think you are talking about glibc, not glib, and the macro in question is the assert macro:

    In glibc's , with NDEBUG (no debugging) defined, assert is defined as:

    #ifdef NDEBUG
    #if defined __cplusplus && __GNUC_PREREQ (2,95)
    # define __ASSERT_VOID_CAST static_cast
    #else
    # define __ASSERT_VOID_CAST (void)
    #endif
    # define assert(expr)           (__ASSERT_VOID_CAST (0))
    #else
    /* more code */
    #endif
    

    which basically means assert(whatever); is equivalent to ((void)(0));, and does nothing.

    From the C89 standard (section 4.2):

    The header defines the assert macro and refers to another macro,

    NDEBUG
    

    which is not defined by . If NDEBUG is defined as a macro name at the point in the source file where is included, the assert macro is defined simply as

    #define assert(ignore) ((void)0)
    

    I don't think defining a debug print macro to be equal to (void)0 makes much sense. Can you show us where that is done?

提交回复
热议问题