Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does casting to `void` really do? [duplicate]

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?

like image 412
Ruslan Avatar asked Dec 15 '15 12:12

Ruslan


People also ask

What does casting to void mean?

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.

What does casting to void pointer do?

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.

What is the point of void C++?

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.


1 Answers

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.

like image 158
Rahul Tripathi Avatar answered Oct 30 '22 14:10

Rahul Tripathi