Scope of enum in C vs C++

后端 未结 3 1674
别跟我提以往
别跟我提以往 2021-01-01 15:53

Why are enum values accessible outside the block in which enum is defined in C, but not in C++?

Consider the following C program.

#include 

        
3条回答
  •  鱼传尺愫
    2021-01-01 16:08

    The answers given by Vlad and Arachtor are good as far as they go, but there is a question they do not address: why C++ does it differently. If someone is familiar with Stroustrup's book, they may be able to improve this, but I suppose:

    • C was designed long ago to be fairly easy to compile, while C++ aims to make programming more reliable by using OO, whose main ideal is “in one place, tell the user of a construct all they need to know to use it and no more”; this has the often unspoken benefit of bringing together what belongs together.
    • This leads to the decisions to use type definitions to limit the scope of some definitions, and to place constructs within a hierarchy of namespaces.
    • By restricting the scope of a nested enum it is possible to use shorter names without risk of ambiguity or clashes.

提交回复
热议问题