What does casting to `void` really do?

Ruslan picture Ruslan · Dec 15, 2015 · Viewed 22.5k times · Source

An often used statement like (void)x; allows to suppress warnings about unused variable x. But if I try compiling the following, I get some results I don't quite understand:

int main()
{
    int x;
    (short)x;
    (void)x;
    (int)x;
}

Compiling this with g++, I get the following warnings:

$ g++ test.cpp -Wall -Wextra -o test
test.cpp: In function ‘int main()’:
test.cpp:4:13: warning: statement has no effect [-Wunused-value]
     (short)x;
             ^
test.cpp:6:11: warning: statement has no effect [-Wunused-value]
     (int)x;
           ^

So I conclude that casting to void is very different from casting to any other types, be the target type the same as decltype(x) or something different. My guess at possible explanations is:

  • It is just a convention that (void)x; but not the other casts will suppress warnings. All the statements equally don't have any effect.
  • This difference is somehow related to the fact that void x; isn't a valid statement while short x; is.

Which of these if any is more correct? If none, then how can the difference in compiler warnings be explained?

Answer

Rahul Tripathi picture Rahul Tripathi · Dec 15, 2015

Casting to void is used to suppress compiler warnings. The Standard says in §5.2.9/4 says,

Any expression can be explicitly converted to type “cv void.” The expression value is discarded.