Thursday, July 12, 2012

What do "(void) var;" and "(void) 0;" mean?

1. (void)var 
It is seen often in AOO. What does it mean?
Maybe to avoid a compilation warning because "var" isn't used?


From:http://stackoverflow.com/questions/6145548/what-is-the-purpose-of-the-statement-voidc


2. (void) 0

Q: 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?
A: (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 anif clause).

From: http://stackoverflow.com/questions/2198950/why-is-void-0-a-no-operation-in-c-and-c


For __noop in MS, see below quotation from MSDN
http://msdn.microsoft.com/en-us/library/s6btaxcs%28VS.80%29.aspx

The __noop intrinsic specifies that a function should be ignored and the argument list be parsed but no code be generated for the arguments. It is intended for use in global debug functions that take a variable number of arguments.


// compiler_intrinsics__noop.cpp
// compile with or without /DDEBUG
#include <stdio.h>
#if DEBUG
#define PRINT printf_s
#else
#define PRINT __noop
#endif
int main() {
PRINT("\nhello\n");
}

3. (void) func()
Consider the following code snippet:


int func(void);
...
(void) func();


Here I'm casting the return value of the function to void. That certainly makes it look like there's a data type called void. In reality, this sort of cast is a special case; it tells the compiler that you want to throw away the return value of the function. The compiler would do that anyway if you hadn't included the cast to void, so cast to void is unnecessary. Some people use it as idiom to tell lint, the compiler, and [most importantly] the maintenance programmers that they knew the function returns a value but deliberately decided to ignore it.






No comments:

Post a Comment