Variable Value (void)

Possible duplicate:
What does void casting do?

I was just looking through the project and found this

//This is in a .cpp file #if xxx == 5 (void)var; #endif 

What does this (void)var do? Any value at the same time. I heard that this has to do with compilation .

Adding both c and cpp tag incase is common.

+4
source share
2 answers
 (void)var; 

This statement does nothing. But it helps in disabling the compiler.

This is mainly done to avoid unused warning variables.


In response to a comment by @vonbrand. This creates situations where it is useful.

  • The function is declared in the header file. But the body of the function has been changed, and one of its parameters is no longer used. But changing the header requires testing another code that uses this header file.
  • A new function is written, but a parameter that is not currently in use will be used when the function is changed later. Otherwise, the prototype of the function must change in the title and definition.

For example, in gcc, when the -Werror compilation option is used by default in the makefile, and it may be undesirable to modify the entire project. In addition, it is completely safe and portable to make (void)var; for any variable. Therefore, I don’t understand why this would be a bad idea that makes life easier for programmers in some situations.

Therefore, it is not always advisable to get rid of unused variables. This will take longer if needed later.

+6
source

The void actuation is performed to avoid the compiler warning about an unused variable.

This can also be done globally using the compiler flag: -Wno-unused-variable.

+3
source

All Articles