为什么是(void)0在C和C ++中没有操作? [英] Why is (void) 0 a no operation in C and C++?

查看:558
本文介绍了为什么是(void)0在C和C ++中没有操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在 glibc 中看到调试printfs,其内部定义为(void)0 ,如果 NDEBUG 定义。同样, __ noop Visual C ++编译器也有。前者用于GCC和VC ++编译器,而后者仅用于VC ++。现在我们都知道上面的语句将被视为无操作,并且不会产生相应的代码;

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 is there too. The former works on both GCC and VC++ compilers, while the latter only on VC++. Now we all know that both the above statements will be treated as no operation and no respective code will be generated; but here's where I've a doubt.

__ noop 的情况下,MSDN说这是一个内在函数提供由编译器。来到(void)0 〜为什么它被编译器解释为无操作?它是一个棘手的使用C语言或标准说的东西关于它的显性吗?

In case of __noop, MSDN says that it's a intrinsic function provided by the compiler. Coming to (void) 0 ~ Why is it interpreted by the compilers as no op? Is it a tricky usage of the C language or does the standard say something about it explicity? Or even that is something to do with the compiler implementation?

推荐答案

(void)0 (+ ; )是一个有效的,但是'does-nothing'C ++表达式,这一切。它不会转换为目标体系结构的 no-op 指令,它只是一个空语句作为占位符,只要语言需要一个完整的语句(例如作为目标跳转标签或如果子句的正文中)。

(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: (根据Chris Lutz的评论更新)

(updated based on Chris Lutz's comment)

请注意,当用作宏时,请说

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

#define noop ((void)0)

c $ c>(void)可防止它被意外地用作像

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

int x = noop;

对于上述表达式,编译器会将其标记为无效操作。 GCC spits 错误:void值不被忽略,因为它应该是和VC ++ barks 'void'非法所有类型

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.

这篇关于为什么是(void)0在C和C ++中没有操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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