The usage of anonymous enums

后端 未结 8 683
无人及你
无人及你 2020-11-29 19:40

What is the purpose of anonymous enum declarations such as:

enum { color = 1 };

Why not just declare int color = 1

8条回答
  •  萌比男神i
    2020-11-29 20:28

    (1) int color = 1;
    

    color is changeable (accidently).

    (2) enum { color = 1 };
    

    color cannot be changed.

    The other option for enum is,

    const int color = 1;  // 'color' is unmutable
    

    Both enum and const int offer exactly same concept; it's a matter of choice. With regards to popular belief that enums save space, IMO there is no memory constraint related to that, compiler are smart enough to optimize const int when needed.

    [Note: If someone tries to use const_cast<> on a const int; it will result in undefined behavior (which is bad). However, the same is not possible for enum. So my personal favorite is enum]

提交回复
热议问题