Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 266
legends2k Avatar asked Feb 04 '10 10:02

legends2k


People also ask

What does void 0 do in C?

This, used with void(0) means, do nothing - don't reload, don't navigate, do not run any code. The "Link" word is treated as a link by the browser. For example, it's focusable, but it doesn't navigate to a new page. 0 is an argument passed to void that does nothing, and returns nothing.

Can a variable be void in C?

A void* pointer can be converted into any other type of data pointer. In C++, a void pointer can point to a free function (a function that's not a member of a class), or to a static member function, but not to a non-static member function. You can't declare a variable of type void .

What is void*) 0 in c++?

(void*)0 is a null pointer constant, whose value is a null pointer of type void* , so by the semantics of parenthesized expressions ((void*)0) also has a value that is a null pointer of type void* . Both (void*)0 and ((void*)0) are address constants.


1 Answers

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

like image 173
Alexander Gessler Avatar answered Sep 20 '22 05:09

Alexander Gessler