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

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

问题描述

可能重复:结果
  为什么(无效)0空操作C和C ++?

在我执行的C ++(Visual Studio 2008中实现)我看到下面的行<&了cassert GT;

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

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

我不明白,需要投0作废。在我看来,那

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

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

甚至干脆

#ifdef  NDEBUG
#define assert(_Expression) 0

会做,考虑到环境中,断言(表达式)可以使用。

那么,什么是0类危险的内部而不是类型0的无效在这种情况下?任何 现实的例子吗?

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

推荐答案

复杂的前pression的唯一目的(无效)0 是为了避免编译器警告。如果你只是有一个赤裸裸的,无用的前pression,编译器会发出警告说没有效果的前pression。但是,通过明确铸造的东西无效表示您的意思是要做到这一点。

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.

(想想这将是用户如何混乱,如果编译器突然说,警告:前pression 0; 没有任何效果。的时候,你所做的一切切换到发布模式。)

(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.)

这也是在C,在那里你会说(空白)的printf常见的做法(你好); 来告诉你有意选择忽略编译器该函数的返回值。

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.

(无效)投是不是由特定的实现仅仅是一种选择;它要求的C标准。引用了2011 ISO C标准(类似的措辞出现在1990年和1999年版):

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):

如果 NDEBUG 是在源文件中的点定义为宏名
  其中, &LT; ASSERT.H&GT; 包括,在 断言 宏被定义为简单

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断言(忽略)((无效)0)

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

C ++标准要求的&LT的内容;了cassert&GT; 头是一样的标准C &LT; ASSERT.H&GT; 头。

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天全站免登陆