const in C vs const in C++

前端 未结 4 1710
滥情空心
滥情空心 2020-12-03 17:57

The given code compiles in C but fails in C++.

int main()
{
   const int x; /* uninitialized const compiles in C but fails in C++*/
}

What

4条回答
  •  情书的邮戳
    2020-12-03 18:10

    The ISO standard says (in 8.5 [dcl.init] paragraph 9):

    If no initializer is specified for an object, and the object is of (possibly cv-qualified) non-POD class type (or array thereof), the object shall be default-initialized; if the object is of const-qualified type, the underlying class type shall have a user-declared default constructor.

    if you try the same example after modifying to this:

    int main()
    {
       /*Unless explicitly declared extern, a const object does not have
     external linkage and must be initialized*/
       extern const int x; 
       return 0;
    }
    

    it will get compiled. So this self explains the need of enforcing this error to c++, declaring const vars without initializing and extern linkage is of no use, so coder must have added it by mistake.

提交回复
热议问题