typedef enum and enum usage

Posted by tsg on Wed, 23 Feb 2022 02:21:25 +0100

typedef enum {
	RESET = 0, 
	SET = !RESET
} FlagStatus, ITStatus; 

This sentence means to alias enum {reset = 0, set =! Reset}: FlagStatus and ITStatus

The FlagStatus and ITStatus that appear after this can be regarded as enum {reset = 0, set =! Reset}

The purpose of this is to save code, improve readability, and be easy to maintain~

1. Define a new data type - enumeration type

The following code defines this new data type - enumeration

enum DAY
{
	MON = 1,
	TUE,
	WED,
	THU,
	FRI,
	SAT,
	SUN
};

(1) An enumeration is a collection in which the elements (enumeration members) are named integer constants separated by commas.
(2) DAY is an identifier, which can be regarded as the name of this collection. It is an optional option, that is, it can be written without writing.
(3) If the value of the first enumeration member is not assigned, the default value is integer 0, and the value of subsequent enumeration members is added with 1 to the previous member. That is, the TUE value in the above code is 2.
(4) You can think of setting the value of enumeration members to customize integers in a range.
(5) Enumeration type is an alternative to preprocessing instruction #define.
(6) Semicolon is used for type definition; end.

2. Use enumeration type to declare variables

Common basic data types are
Integer int, single precision floating-point float, double precision floating-point double, character char, short integer short. These basic data types usually declare variables as follows:

char a; // The type of variable a is char
int x,y,z;//Variables x, y, z are of type int
double m,n;//The type of the variable resul is double precision floating-point double

Enumerative types and methods are defined separately

enum DAY
{
	MON = 1,
	TUE,
	WED,
	THU,
	FRI,
	SAT,
	SUN
};

enum DAY today;//The variable today type is enum DAY	
enum DAY good_day,bad_day;//Variable good_day and bad_ The type of day is enum DAY

Method 2: type definition and variable declaration are carried out at the same time

enum  //DAY is omitted here
{
	MON = 1,
	TUE,
	WED,
	THU,
	FRI,
	SAT,
	SUN
}workday;//The type of the variable workday is enum DAY

enum BOOLEAN
{
	false,
	true
}end_flag,match_flag;//Defines an enumeration type and declares two enumeration variables

Method 3: use the typedef keyword to define the enumeration type as an alias, and use the alias to declare variables

typedef enum workday
{
	MON = 1,
	TUE,
	WED,
	THU,
	FRI,
	SAT,
	SUN
}workday; //Workday here is the alias of enum workday

workday today, tomorrow; //The types of variables today and tomorrow are enumerative workday, i.e. enum workday

It can also be expressed like this

typedef enum 
{
	MON = 1,
	TUE,
	WED,
	THU,
	FRI,
	SAT,
	SUN
}workday; //Workday here is the alias of enum workday

workday today, tomorrow; //The types of variables today and tomorrow are enumerative workday, i.e. enum workday

Or this expression

typedef enum workday
{
	MON = 1,
	TUE,
	WED,
	THU,
	FRI,
	SAT,
	SUN
}; 

workday today, tomorrow; //The types of variables today and tomorrow are enumerative workday, i.e. enum workday

Error declaration

Note: enumeration types with the same name cannot be defined in the same program, and named constants with the same name cannot exist in different enumeration types. Examples of errors are as follows:
Error declaration 1: there is an enumeration type with the same name

typedef enum
{
    wednesday,
    thursday,
    friday
} workday;

typedef enum WEEK
{
    saturday,
    sunday = 0,
    monday,
} workday;

Error declaration 2: there is an enumeration member with the same name

typedef enum
{
    wednesday,
    thursday,
    friday
} workday_1;

typedef enum WEEK
{
    wednesday,
    sunday = 0,
    monday,
} workday_2;

3. Use variables of enumeration type

3.1 assign values to enumerated variables.

The example compares the assignment of enumeration type with that of basic data type:

Method 1: declare the variable first, and then assign a value to the variable

#include<stdio.h>

enum DAY 
{ 
	MON=1,
	TUE,
	WED,
	THU,
    FRI,
    SAT,
    SUN 
    };

void main()
{
    int x, y, z;
    x = 10;
    y = 20;
    z = 30;
 
    enum DAY yesterday, today, tomorrow;
       
    yesterday = MON;
    today     = TUE;
    tomorrow  = WED;

    printf("%d %d %d \n", yesterday, today, tomorrow);
}

Method 2: declare variables and assign initial values at the same time

#include <</SPAN>stdio.h>

enum DAY { MON=1, TUE, WED, THU, FRI, SAT, SUN };

void main()
{
    int x=10, y=20, z=30;
    
    enum DAY yesterday = MON, 
                        today = TUE,
                   tomorrow = WED;

    printf("%d %d %d \n", yesterday, today, tomorrow);
}

Method 3: declare variables while defining types, and then assign values to variables.

#include <stdio.h>

enum DAY { MON=1, TUE, WED, THU, FRI, SAT, SUN } yesterday, today, tomorrow;

int x, y, z;

void main()
{
    
    x = 10;  y = 20;  z = 30;
    yesterday = MON;
    today     = TUE;
    tomorrow  = WED;

    printf("%d %d %d \n", x, y, z); //Output: 10 20 30
    printf("%d %d %d \n", yesterday, today, tomorrow); //Output: 1 2 3
}

Method 4: type definition, variable declaration and initial value assignment are carried out at the same time.

#include <</SPAN>stdio.h>

enum DAY
{
    MON=1, 
    TUE,
    WED,
    THU,
    FRI,
    SAT,
    SUN 
}
yesterday = MON, today = TUE, tomorrow = WED;

int x = 10, y = 20, z = 30;

void main()
{
    printf("%d %d %d \n", x, y, z); //Output: 10 20 30
    printf("%d %d %d \n", yesterday, today, tomorrow); //Output: 1 2 3
}

3.2 when assigning integer values to enumerated variables, type conversion is required.

#include <stdio.h>

enum DAY { MON=1, TUE, WED, THU, FRI, SAT, SUN };

void main()
{
    enum DAY yesterday, today, tomorrow;

    yesterday = TUE;
    today = (enum DAY) (yesterday + 1); //Type conversion
    tomorrow = (enum DAY) 30; //Type conversion
    //tomorrow = 3; // error

    printf("%d %d %d \n", yesterday, today, tomorrow); //Output: 2 3 30
}

3.3 using enumerated variables

#include<</SPAN>stdio.h>

enum
{ 
    BELL          = '\a',
    BACKSPACE = '\b',
    HTAB         = '\t',
    RETURN      = '\r',
    NEWLINE    = '\n', 
    VTAB         = '\v',
    SPACE       = ' '
};

enum BOOLEAN { FALSE = 0, TRUE } match_flag;

void main()
{
    int index = 0;
    int count_of_letter = 0;
    int count_of_space = 0;

    char str[] = "I'm Ely efod";

    match_flag = FALSE;

    for(; str[index] != '\0'; index++)
        if( SPACE != str[index] )
            count_of_letter++;
        else
        {
            match_flag = (enum BOOLEAN) 1;
            count_of_space++;
        }
    
    printf("%s %d times %c", match_flag ? "match" : "not match", count_of_space, NEWLINE);
    printf("count of letters: %d %c%c", count_of_letter, NEWLINE, RETURN);
}

Output:

match 2 times
count of letters: 10
Press any key to continue
  1. Enumeration type and sizeof operator
#include<stdio.h>

enum escapes
{ 
    BELL      = '\a',
    BACKSPACE = '\b',
    HTAB      = '\t',
    RETURN    = '\r',
    NEWLINE   = '\n', 
    VTAB      = '\v',
    SPACE     = ' '
};

enum BOOLEAN { FALSE = 0, TRUE } match_flag;

void main()
{
    printf("%d bytes \n", sizeof(enum escapes)); //4 bytes
    printf("%d bytes \n", sizeof(escapes)); //4 bytes

    printf("%d bytes \n", sizeof(enum BOOLEAN)); //4 bytes
    printf("%d bytes \n", sizeof(BOOLEAN)); //4 bytes
    printf("%d bytes \n", sizeof(match_flag)); //4 bytes

    printf("%d bytes \n", sizeof(SPACE)); //4 bytes
    printf("%d bytes \n", sizeof(NEWLINE)); //4 bytes
    printf("%d bytes \n", sizeof(FALSE)); //4 bytes
    printf("%d bytes \n", sizeof(0)); //4 bytes
}
  1. Comprehensive examples
#include<</SPAN>stdio.h>

enum Season              //Note that if you put it below, you can't directly declare it later
{
    spring, summer=100, fall=96, winter
};

typedef enum
{
    Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
}
Weekday;

void main()
{
    
    printf("%d \n", spring); // 0
    printf("%d, %c \n", summer, summer); // 100, d
    printf("%d \n", fall+winter); // 193

    Season mySeason=winter;                //That's it. According to the above definition, you can also enum Season mySeason
    if(winter==mySeason)
        printf("mySeason is winter \n"); // mySeason is winter
    
    int x=100;
    if(x==summer)
        printf("x is equal to summer\n"); // x is equal to summer

    printf("%d bytes\n", sizeof(spring)); // 4 bytes

    
    printf("sizeof Weekday is: %d \n", sizeof(Weekday)); //sizeof Weekday is: 4

    Weekday today = Saturday;
    Weekday tomorrow;
    if(today == Monday)
        tomorrow = Tuesday;
    else
        tomorrow = (Weekday) (today + 1); //remember to convert from int to Weekday
}

This article draws on the article of CSDN blogger "ppaiml", and the original link is: https://blog.csdn.net/yuantuo3887/article/details/79211313

Topics: C