Some good example for using enums

后端 未结 10 1612
感情败类
感情败类 2021-01-05 06:28

I learned enums when I learned C and from time to time I keep myself reminding about it and most of the time by re-reading from some source,it occurred to me that this is d

10条回答
  •  一个人的身影
    2021-01-05 07:06

    enums can make code easier to read and may present better type checking during compilation.

    Issues With Enums

    1. They can be converted to int or unsigned int and assigned into those kind of variables, thus creating a hole in the type checking benefit.
    2. Their symbol name cannot be printed directly. Passing an enum to std::cout results in the enum converted to an integer then printed out. Most implementations must perform a table lookup to convert the enum to text before printing.

    Alternatives

    Another alternative to enum is to use a string. I've worked at shops where they pass a constant string instead of an enum. One advantage is that the named value is always available, even when debug symbols are not. Also there are no conversions required when printing.

    Some disadvantages to strings:

    1. Can't be used in switch statement.
    2. Case sensitivity when comparing.
    3. Comparing may take more execution time.
    4. Occupies more data or executable space.

提交回复
热议问题