Manage your Constant’s List More Easily By using Enums.

18 11 2008


List of constants and their count. Every programmer have used it atleast once in his life time. A list of constants can be any for instance, if its an image processing software, it can be a list of image types, the application can manage. And we also used to keep the count of constants present.

manageconstantlistasenum2

Yes. I know you need an example. Well, lets take the image processing application itself. It might keep a constant list as follows.

const int IMAGE_TYPE_BMP = 0;
const int IMAGE_TYPE_JPG = 1;
const int IMAGE_TYPE_GIF = 2;
const int IMAGE_TYPE_COUNT = 3;

Think what all you’ve to do if you need to add a new image type? You’ve to insert the constant at end, then update the count. Like this,

const int IMAGE_TYPE_BMP = 0;
const int IMAGE_TYPE_JPG = 1;
const int IMAGE_TYPE_GIF = 2;
const int IMAGE_TYPE_JPG_LOSSY = 3;
const int IMAGE_TYPE_COUNT = 4;

If you want to append the variable, its okay. You just have to append at end and update the count. But what if you want to insert the variable at middle? In this case JPG_LOSSY seems to be more good just after the JPG. isn’t it? In that case you’ve to update all following constants.Like this,

const int IMAGE_TYPE_BMP = 0;
const int IMAGE_TYPE_JPG = 1;
const int IMAGE_TYPE_JPG_LOSSY = 2;
const int IMAGE_TYPE_GIF = 3;
const int IMAGE_TYPE_COUNT = 4;

Assume if your constant list have 50 items! Well, is there any easy trick?


Yes! You can use anonymous enums to avoid the headache. Just declare the constants as follows.

enum
{
IMAGE_TYPE_BMP = 0,
IMAGE_TYPE_JPG,
IMAGE_TYPE_GIF,
IMAGE_TYPE_COUNT
};

And if you want to insert another constant at middle, just insert it. You don’t have to modify anything else. For instance,

enum
{
IMAGE_TYPE_BMP = 0,
IMAGE_TYPE_JPG,
IMAGE_TYPE_JPG_LOSSY,
IMAGE_TYPE_GIF,
IMAGE_TYPE_COUNT
};


Since, they are anonymous enums, you can use the constant name directly in code.
Just insert and forget the rest. It will get self adjusted. ๐Ÿ˜€ Cool! isn’t it.


Targeted Audience – Intermediate.

Advertisements

Actions

Information

2 responses

20 11 2008
cppkid

Nice explanation. Cheers. ๐Ÿ™‚

20 11 2008
Jijo.Raj

Thanks cppkid! Keep watching.

Regards,
Jijo.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s




%d bloggers like this: