Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting to void (not pointer) is allowed, why?

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?

like image 708
Dean Avatar asked Sep 28 '15 17:09

Dean


People also ask

What does casting to void pointer do?

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.

Should you cast a void pointer?

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.

Can you cast anything to a void *?

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.

What is one reason you would use a void pointer?

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.


1 Answers

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

like image 62
Andrew Avatar answered Oct 26 '22 14:10

Andrew