C zero-based enumeration video -43-

[TOC]

# Flag variable in certain programming situations, we may appear multiple branch According to a variable, we often use a state flag variable storage branches, such as:

#include <stdio.h>


int main(int argc, char* argv[])
{
    int nChoice = -1;
    scanf("%d", &nChoice);
    switch (nChoice)
    {
    case 0:
        printf("选择0号菜单,运行增加功能……\r\n");
        break;
    case 1:
        printf("选择1号菜单,运行删除功能……\r\n");
        break;
    case 2:
        printf("选择2号菜单,运行查询功能……\r\n");
        break;
    }
    return 0;
}

# Enumeration, however, a simple digital readability is not good, then, we can use enumerations to enhance readability. Enum keyword is enum, with struct, union Similarly, we need to define a new enumeration type, then the enumeration type to define enumeration.

#include <stdio.h>

enum FLAG_CHOICE{
    ADD,
    DEL,
    QUERY
};

int main(int argc, char* argv[])
{
    FLAG_CHOICE myChoice;
    return 0;
}

As can be seen, the use of enum type declarations, also need to declare their support for this type of a variety of "state." After enumeration defined, it will only be defined by the state assignment:

#include <stdio.h>

enum FLAG_CHOICE{
    ADD,
    DEL,
    QUERY
};

int main(int argc, char* argv[])
{
    FLAG_CHOICE myChoice;
    myChoice = ADD; //合法
    myChoice = DEL; //合法
    myChoice = QUERY; //合法

    myChoice = 5; //非法
    return 0;
}

Use enumeration can be made to enhance the readability of the code:

#include <stdio.h>

enum FLAG_CHOICE{
    ADD,
    DEL,
    QUERY
};

int main(int argc, char* argv[])
{
    FLAG_CHOICE myChoice;
    scanf("%d", &myChoice);

    switch (myChoice)
    {
    case ADD:
        printf("增加功能...\r\n");
        break;
    case DEL:
        printf("删除功能...\r\n");
        break;
    case QUERY:
        printf("查询功能...\r\n");
        break;
    }
    return 0;
}

# Enumeration is essentially a digital code that can be seen from the above

    FLAG_CHOICE myChoice;
    scanf("%d", &myChoice);

This can compile, because of the nature of the enumeration is actually an integer type. After just defined enumerated types, the compiler will do two things:

  • When enumeration type declaration, the states into digital (starting with subscript 0)
  • When enumerating variable assignment, will be forced to do the type checking, enumeration type declaration does not state (digital), shall not be assigned

Because of this, when an enumeration type declaration, you can also specify the figures.

enum FLAG_CHOICE{
    ADD = 2,
    DEL = 1,
    QUERY = 0
};

Guess you like

Origin www.cnblogs.com/shellmad/p/11695682.html