13

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?

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
Dean
  • 6,610
  • 6
  • 40
  • 90

1 Answers1

17

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

Andrew
  • 5,212
  • 1
  • 22
  • 40
  • What is ambiguous about `(void)expr;`? Is it just because _Don't use C-casts_ or is there an actual reason to avoid the C-cast version? – nwp Sep 28 '15 at 17:26
  • 1
    @nwp - just the usual [reasons to avoid C-style casts](http://stackoverflow.com/a/32224/3852968). Nothing special about casting to void. – Andrew Sep 28 '15 at 17:26
  • 5
    But none of the usual reasons apply here. There is no conversion taking place so the kind of conversion doesn't even make sense. There is no reason to search for the cast since it doesn't do anything besides shutting up a compiler warning. There is no masking of weak code. This is just following the rules for the rule's sake, not for a purpose. – nwp Sep 28 '15 at 17:33
  • 1
    Using `static_cast` is rather awkward, the syntax `(void)` is much better imo. And there's no difference between them. – edmz Sep 28 '15 at 17:33
  • Still a good idea to confirm to new C++ standards in the case of the older standards becoming deprecated. – otc Sep 28 '15 at 17:35
  • @nwp, @black: That's entirely a matter of style. I don't want to get into a debate on style here. `static_cast` and `(void)` both work, and yes, the usual reasons don't really fit strongly here. I prefer to use C++ named casts everywhere, that's all. – Andrew Sep 28 '15 at 17:36