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

前端 未结 5 2136
情歌与酒
情歌与酒 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:27

    (void)0 (+;) is a valid, but 'does-nothing' C++ expression, that's everything. It doesn't translate to the no-op instruction of the target architecture, it's just an empty statement as placeholder whenever the language expects a complete statement (for example as target for a jump label, or in the body of an if clause).

    EDIT: (updated based on Chris Lutz's comment)

    It should be noted that when used as a macro, say

    #define noop ((void)0)
    

    the (void) prevents it from being accidentally used as a value like

    int x = noop;
    

    For the above expression the compiler will rightly flag it as an invalid operation. GCC spits error: void value not ignored as it ought to be and VC++ barks 'void' illegal with all types.

提交回复
热议问题