Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between (void)obj and void(obj)

Tags:

c++

casting

void

According to http://en.cppreference.com/w/cpp/language/explicit_cast, C-style cast and functional cast are equivalent. However, see the following example:

#include <array>
int main() {
  std::array<int, 3> arr{};
  (void)arr;
  //void(arr);
}

While (void)arr compiles, void(arr) does not. What have I missed?

like image 698
Lingxi Avatar asked Jan 10 '23 04:01

Lingxi


2 Answers

If there are no ambiguities (e.g. other functions with the same name, macros..) involved, the following code declares and defines two int variables

int a = 22;
int (b) = 33;

thus you're trying to create a void variable type (with an existing name).

And that's wrong because:

  1. You're trying to create a void variable

  2. You're trying to use an existing name for another variable in the same scope

like image 81
Marco A. Avatar answered Jan 19 '23 21:01

Marco A.


While void(arr) is usually the same as (void)arr, in this context it is a definition, and you are trying to create a variable called arr of type void, which isn't allowed.

like image 45
Simple Avatar answered Jan 19 '23 22:01

Simple