浇铸0到void [英] casting 0 to void

查看:207
本文介绍了浇铸0到void的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:






在我的C ++实现(Visual Studio 2008实现)中,我看到< cassert>

  #ifdef NDEBUG 
#define assert(_Expression)((void)0)

我不明白需要将0转换为void。在我看来,

  #ifdef NDEBUG 
#define assert(_Expression)(0)

或甚至

  #ifdef NDEBUG 
#define assert(_Expression)0

其中 assert(expr)可以使用。



int ,而不是类型 void 的0?

解决方案

复杂表达式的唯一目的(void)0 是为了避免编译器警告。如果你只有一个裸露的,无用的表达式,编译器可能会警告一个没有效果的表达式。但是通过显式地将一些东西转换为 void ,你就表示你的意思是这样做。



如果编译器突然说,警告:表达式 0; 没有效果。,当你所做的全部切换到释放模式) / p>

这也是C的常用做法,你可以说(void)printf(Hello); 告诉编译器你有意选择忽略函数的返回值。



(void) cast不仅仅是特定实施的选择;它是C标准要求的。引用2011年ISO C标准(类似的措辞出现在1990和1999版本):


如果 NDEBUG 定义为源文件中的点处的宏名称
其中 < assert.h> ,则 assert 宏定义为



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



b $ b

C ++标准要求< cassert> 头的内容与标准C < assert相同。 h> 标题。


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

On my implementation of C++ (Visual Studio 2008 implementation) I see the following line in <cassert>

#ifdef  NDEBUG
#define assert(_Expression) ((void)0)

I do not understand the need to cast 0 to void. It seems to me that

#ifdef  NDEBUG
#define assert(_Expression) (0)

or even simply

#ifdef  NDEBUG
#define assert(_Expression) 0

would do, considering the contexts in which assert(expr) can be used.

So, what's the danger of 0 of type int instead of 0 of type void in this case? Any realistic examples?

解决方案

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.

这篇关于浇铸0到void的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆