Hi dude,
This code isn't portable and makes some assumptions which are reasons for your compiler to complain
1) ints aren't always 32 bits (not such a big deal for most platforms)
2) Under C++, enumerations don't have to be ints - the implementation is free to decide the best size for a given enumeration - not really a problem in your code since the logical size would need to be 4-bytes in this case
3) Multicharacter constants are not uniformly supported. How they map to integers may additionally depend on endian issues that are obviously hardware dependent.
If the actual value of your constants isn't imporant to you (as long as theyre unique), just use a normal enumeration which ensures each constant has a unique value.
If you want to enforce an enumeration size to make sure it's 32-bits, you could use something like
enum {
JOHN_NAME,
FRED_NAME,
MIKE_NAME,
ANNE_NAME,
DUMMY_NAME = 0xFFFFFFFF
};
Another option to generate a unique number from a string name is to use a hash function.
Here's one I made earlier :-)
unsigned long GetHashValue(const char* text)
{
unsigned long v = 0;
unsigned char* p = (unsigned char*)text;
while(*p) {
/* bitwise rotate and xor with byte */
v = (v<<1) | ((v&0x80000000UL) ? 1UL : 0);
v ^= (unsigned long) (*p++);
}
return v;
}
This generates different values for different strings and has lots of uses.
For a slightly off topic example, I use the above (in a class form) to generate integers from filenames as part of a cacheing system - rather than looking through a list of names (using strcmp()), to see if something is loaded, I generate the hash for each loaded object and search by hash value. Much faster :-)