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 whileshort x;
is.
Which of these if any is more correct? If none, then how can the difference in compiler warnings be explained?
void
and casts to other types, while the other asks about why one would want to do the cast tovoid
. However, since this question has a satisfactory answer, I won't bother to alter it and vote to reopen. This comment is just to answer the auto-generated "Does this answer your question?". TLDR: nope. – Auxin