5

Possible Duplicate:
What does void casting do?

I was just browsing through a project and found this

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

What does this (void)var do? Any significance on doing this. I have heard that this has something to do with compilation.

Adding both c and cpp tag incase this is common.

Community
  • 1
  • 1
sr01853
  • 6,043
  • 1
  • 19
  • 39

2 Answers2

9
(void)var;

This statement does effectively nothing. But helps in silencing compiler.

It's mainly done to avoid unused variable warnings.


In reply to @vonbrand's comment. Here are made up situations where this is useful.

  • The function is declared in a header file. But the function body has been modified and one of its parameter is no longer used. But modifying header be require testing other code that's using this header file.
  • A new function is written but the parameter that's currently unsed will be used when the function is modifed later. Otherwise, the function prototype is required to modify in the header and in the definition.

For example in gcc, when the compilation option is -Werror is used by default in the makefile and it may not be desirable to modify for the whole project. Besides, it's completely harmless and portable to do (void)var; for any variable. So I don't see why it would be a bad idea which helps programmers life easier in some situations.

So it's not always desirable to get rid of unused variables. Doing so would require more work when later needed.

P.P
  • 117,907
  • 20
  • 175
  • 238
  • 1
    And shutting up the compiler by such kludges is a _bad_ idea. Get rid of the useless variable (this uses conditional compilation to shut the compiler up, use the same logic to get rid of the variable for good). Whatever makes the compiler complain today (and you can prove it isn't a problem) can result in a disastrous situation _without_ warning (turned off by the kludge) as the code changes. – vonbrand Jan 29 '13 at 13:48
  • 2
    @vonbrand it's not always that easy. For a hobby ray-tracer project I have a function in each texture class that takes a set of UV coordinates. In some textures those parameters are not required. That doesn't mean the design is wrong, though. – Alnitak Jan 29 '13 at 14:04
  • @vonbrand It's not always desirable or easy to get rid of ununsed variables in complex projects. I updated my answer with some reasons. – P.P Jan 29 '13 at 14:16
  • @KingsIndian, that it isn't easy doesn't make it right to kluge around compiler warnings. In my (hard earned) experience it is cheaper in the long run to fix such annoyances _right_. – vonbrand Jan 29 '13 at 14:41
3

The casting to void is done to avoid the compiler's warning about the unused variable.

This can also be done on a global level using the compiler's flag: -Wno-unused-variable.

Alex Bitek
  • 6,529
  • 5
  • 47
  • 77