Why can I cast this vector to a void (not even a pointer)?
int main()
{
std::vector<int> a;
(void)a;
}
How come this is allowed?
static_cast converts the pointer of the void* data type to the data type of that variable whose address is stored by the void pointer. In the above example, we used static_cast to convert the void pointer into an int pointer, so that we could print the contents of the variable var.
There are two correct cases where you need to have a cast: to convert a pointer to a void back to its original non-void type without assigning the result to a variable (assignment including initialization, or passing it as an argument). to silence a stupid compiler that gives a warning about a narrowing conversion.
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.
Why do we use a void pointer in C programs? We use the void pointers to overcome the issue of assigning separate values to different data types in a program. The pointer to void can be used in generic functions in C because it is capable of pointing to any data type.
Casting to void simply discards the result of the expression. Sometimes, you'll see people using this to avoid "unused variable" or "ignored return value" warnings.
In C++, you should probably write static_cast<void>(expr);
rather than (void)expr;
This has the same effect of discarding the value, while making it clear what kind of conversion is being performed.
The standard says:
Any expression can be explicitly converted to type cv void, in which case it becomes a discarded-value expression (Clause 5). [ Note: however, if the value is in a temporary object (12.2), the destructor for that object is not executed until the usual time, and the value of the object is preserved for the purpose of executing the destructor. —end note ]
ISO/IEC 14882:2011 5.2.9 par. 6
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