Why can't we declare a variable of type void?

后端 未结 7 1655
盖世英雄少女心
盖世英雄少女心 2020-12-08 09:43

I\'m looking for a formal explanation of that fact in the Standard. I\'ve found what 3.9.1/9 says and trying to give an explanation used that section.

S

7条回答
  •  误落风尘
    2020-12-08 10:19

    Well - I really don't see the rationale behind this. It's going to be great if this way we can declare a variable with unknown type. Something like 'void *' and arrays of unknown size. Imagine code like this:

    #include 
    #include 
    
    using namespace std;
    
    extern void f;
    
    int main()
    {
        cout << (int &)f << endl; //cout 'f' as it was integer
    }
    
    struct {
        int a;
        double b;
    } f{};
    

    You can now actually do something similar with arrays:

    #include 
    #include 
    
    using namespace std;
    
    struct Foo;
    
    extern int arr[];
    
    int main()
    {
        cout << arr[2] << endl;
    }
    
    int arr[4]{};
    

    Life example.

提交回复
热议问题