casting 0 to void

∥☆過路亽.° 提交于 2019-12-04 01:28:13
Kerrek SB

The only purpose of the complicated expression (void)0 is to avoid compiler warnings. If you just had a naked, useless expression, the compiler might warn about an expression that has no effect. But by explicitly casting something to void you indicate that you mean to do this.

(Think about how confusing it would be to the user if the compiler suddenly said, "Warning: expression 0; has no effect.", when all you've done is switched to release mode.)

This was also common practice in C, where you'd say (void)printf("Hello"); to tell the compiler that you intentionally chose to ignore the return value of the function.

The (void) cast is not merely a choice by a particular implementation; it's required by the C standard. Quoting the 2011 ISO C standard (similar wording appears in the 1990 and 1999 editions):

If NDEBUG is defined as a macro name at the point in the source file where <assert.h> is included, the assert macro is defined simply as

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

The C++ standard requires the contents of the <cassert> header to be the same as the Standard C <assert.h> header.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!