开发者

ENUM constants questions

It was posted on this site how you could generate unique enum constants by doing the following:

enum _EXAMPLE
{
  开发者_如何转开发  LEFT = 'left',
    RIGHT = 'right'
    //etc
};

Ignoring the issue of validity, how are the numbers generated? More specifically, what technique is used? As I wish to try to build a function that emulates it for short strings.


'left' is a multicharacter literal (2.13.2/1 of C++03), it has type int.

It's implementation-defined what integer value it actually has. In particular, there's no guarantee that 'left' and 'right' aren't equal, so you're on to something of a loser using them in an enum.

For an example, though, GCC documents its behavior here: http://gcc.gnu.org/onlinedocs/gcc-4.6.1/cpp/Implementation_002ddefined-behavior.html#Implementation_002ddefined-behavior

'right' has five characters, and clearly it's not possible for every 5-character string to have a different 32 bit value.


A multi-character constant is something you'd usually want to avoid. Let's say your system is little-endian with 32-bit architecture. In that case, 'left' translates to:

('l')+('e'<<8)+('f'<<16)+('t'<<24)

Note that for it to be easier to read, I omitted a cast to int behind each of the characters.

So the multi-character constant is actually an integer.

I once used 'BM' to check the first two bytes of a .bmp image I read to check if the filetype is correct, but soon I decided it's not worth the extra few characters I'm saving. If you go on a big-endian system, or your int has a different size etc etc, you will get a problem there. Not to mention the annoying compiler warning.

If you have an enum, there are usually two cases:

Case 1, you don't care about the values of the enum. In that case, you just leave them be. The first one will become zero and the compiler fill the rest incrementally.

Case 2, you need those values for a clever purpose. In that case, you need to assign them one by one for you purpose. For example, if you want to enum your program's subsystems and you need to enable, disable them, you could have 1 variable which is the or (|) of enum values like this:

enum subsystem
{
    SUBSYSTEM_1 = 0x0001,
    SUBSYSTEM_2 = 0x0002,
    SUBSYSTEM_3 = 0x0004,
    SUBSYSTEM_4 = 0x0008,
    SUBSYSTEM_5 = 0x0010,
    /* etc */
};

(fun fact, did you know that C++ accepts the extra , after the last element of enum?)

In none of the cases you would want a strange value that corresponds to 'left'. If you think that makes the code clear to read, you can be sure the name of the constant (LEFT) is certainly enough.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜