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.

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

C++相关问答推荐

海湾合作委员会是否保证大小匹配的访问?

我可以动态分配具有空类型函数的矩阵吗?

segfault在C中使用getline()函数

括号中的堆栈实现错误问题

空指针的运行时强制转换

C编译器是否遵循restrict的正式定义?

ATmega328P EEPROM未写入

如何使解释器存储变量

RawMotion的XInput2错误(具有较高值的XISelectEvents上的BadValue)

为什么数组的最后一个元素丢失了?

从C文件中删除注释

如何读取文件并将内容保存在字符串中?(在C语言中,没有崩溃或核心转储错误)

将变量或参数打包到 struct /联合中是否会带来意想不到的性能损失?

将回调/基于事件的C API转换为非回调API

这段代码用于在C中以相反的顺序打印数组,但它不起作用

我编写这段代码是为了判断一个数字是质数、阿姆斯特朗还是完全数,但由于某种原因,当我使用大数时,它不会打印出来

将size_t分配给off_t会产生符号转换错误

在同一范围内对具有相同类型的变量执行的相同操作在同一C代码中花费的时间不同

macos/arm64 上地址空间不使用第一位吗?

将字节/字符序列写入标准输出的最简单形式