Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Significance of (void)variable [duplicate]

Tags:

c++

c

void

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.

like image 769
sr01853 Avatar asked Dec 27 '22 10:12

sr01853


1 Answers

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

like image 50
P.P Avatar answered Jan 09 '23 02:01

P.P