Using enumerations to represent status codes

Source: Internet
Author: User

Enumerations are just a constant naming method. The various states that an object undergoes can be defined as a simple set of enumerations.

For example:

enum eocconnectionstate {   eocconnectionstatedisconnected,   eocconnectionstateconnecting,   Eocconnectionstateconnected,};

Since each state is represented by an understandable value, the code that is written is easier to read.

The compiler assigns a unique number to the enumeration, starting with 0 and incrementing by 1 for each enumeration.

The data type used to implement the enumeration depends on the compiler, but the number of bits must be fully represented under the enumeration number.

In, because the maximum number is 2, use a 1-byte char type.

But the wording is very not concise.

enum Eocconnectionstate state = eocconnectionstatedisconnected;

So we often use the following notation

typedef ns_enum (Nsuinteger, eocconnectionstate) {  eocconnectionstatedisconnected,  Eocconnectionstateconnecting,     eocconnectionstateconnected,};

Points:

1. An enumeration should be used to indicate the state of the state machine, the status code equivalent, and give these values an understandable name

2. If the option passed to a method is expressed as an enumeration type, and multiple options can be used simultaneously, then each option value is defined as a power of 2 to be combined by bitwise OR operation

3. Use the Ns_enum macro to define the enumeration type and indicate the underlying data type, which ensures that the enumeration is implemented by the developer's chosen data type and not by the compiler's chosen type.

4. Do not implement the default branch when dealing with a switch statement of an enumeration type, so that when a new enumeration is added, the developer is prompted: The switch statement does not handle all branches.

Using enumerations to represent status codes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.