The usage of anonymous enums

后端 未结 8 691
无人及你
无人及你 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条回答
  •  隐瞒了意图╮
    2020-11-29 20:23

    Enums don't take up any space and are immutable.

    If you used const int color = 1; then you would solve the mutability issue but if someone took the address of color (const int* p = &color;) then space for it would have to be allocated. This may not be a big deal but unless you explicitly want people to be able to take the address of color you might as well prevent it.

    Also when declaring a constant field in a class then it will have to be static const (not true for modern C++) and not all compilers support inline initialization of static const members.


    Disclaimer: This answer should not be taken as advice to use enum for all numeric constants. You should do what you (or your co-workers) think is more readable. The answer just lists some reasons one might prefer to use an enum.

提交回复
热议问题