enum

  • enum枚举,Enumeration (or enum) is a user defined data type in C. It is mainly used to assign names to integral constants, the names make a program easy to read and maintain.
  • code implements: ```c /**
  • declaration */

enum test { mon, // state = 0 tue, // state = 1 wed, // state = 2 and so on. By default the compiler assigns values starting by 0 tur, fri, sat, sun
};

// we can use typedef to make enum clearer typedef enum test { mon, tue, wed, tur, fri, sat, sun
}test;

// We can assign values to some name in any order. // All unassigned names get value as value of previous name plus one. enum test { mon, tue = 10, wed, // state = 11 tur, // state = 12 fri = 20, sat, // state = 21 sun };

// All enum constants must be unique in their scope. // For example, the following program fails in compilation. enum test {faild, passed}; enum okkk {tested, failed};

/**

  • instantiation */ int main() { enum test day; }

// if you rename enum with typedef int main() { test day;
}

/**

  • operation */ int main(){ enum test day; day = mon; day = tue; } ```

    interesting point: macro VS enum

    • enum can only define integral values, but it can follow scope rules and automatically assigned values.
    • macro can define all kind of values, because it just do copy and paste during compiling time.