Tuesday, January 15, 2008

enum

traditional C way of doing this was something like this:
#define SPRING 0
#define SUMMER 1
#define FALL 2
#define WINTER 3

An alternate approach using enum would be
enum { SPRING, SUMMER, FALL, WINTER };

You can also use:
enum MyEnumType { ALPHA, BETA, GAMMA };
enum MyEnumType x; /* legal in both C and C++ */
MyEnumType y; // legal only in C++

you may provide explicit values for enum constants, as in
enum FooSize { SMALL = 10, MEDIUM = 100};
enum {MAX_POINT = 10}

There is an implicit conversion from any enum type to int. Suppose this type exists:
enum MyEnumType { ALPHA, BETA, GAMMA };

Then the following lines are legal:
int i = BETA; // give i a value of 1
int j = 3 + GAMMA; // give j a value of 5

[update Nov. 30, 09]
The enumeration constant is plain integer.
1. Cannot use for floating constant: enum{PI=3.14}, it will truncate it to 3
2. Even you write enum {AAA = 1234U}, it is still integer, not unsigned integer.

enum obeys the scope rule, and it is compile-time constant, so you can use:
char buffer[AAA];
But if you use constant object like:
const int AAA = 1234;
char buff[AAA];

It only compiles in C++ (error in C) since const object is a compile-time constant expression in C++. In C, it is not.

No comments:

Post a Comment