const in C vs const in C++

前端 未结 4 1709
滥情空心
滥情空心 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:25

    Note that there is a legitimate use of an uninitialized, const-qualified object of automatic storage duration: its address can be taken and used as a unique key for labeling recursion levels in a recursive function. This is somewhat obscure, but worth noting. C makes this use efficient, while C++ requires you waste time and code size on initializing it. (In theory the compiler could perhaps determine that the value is never used and optimize out the initialization, but since you're passing around a pointer, that would be rather difficult to prove.)

提交回复
热议问题