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:
(void)x;
but not the other casts will suppress warnings. All the statements equally don't have any effect.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?
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. Follow this answer to receive notifications.
A void pointer is a pointer that can point to any type of object, but does not know what type of object it points to. A void pointer must be explicitly cast into another type of pointer to perform indirection. A null pointer is a pointer that does not point to an address. A void pointer can be a null pointer.
When used for a function's parameter list, void specifies that the function takes no parameters. When used in the declaration of a pointer, void specifies that the pointer is "universal." If a pointer's type is void* , the pointer can point to any variable that's not declared with the const or volatile keyword.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With