#define, const global variable and enum

There are 3 ways to define integer values for certain setting.
We are going back to freshman class. :)
For example, let’s assume this case.

switch( videoFormat )
{
    ....
}

How to define values which are set to videoFormat variable?
There are 3 ways to do so.

  1. #define
  2. enum
  3. const global variable

I found out that people use #define a lot. I also use #define sometimes. But it has some bad side.
First, its type can’t be checked by compiler. Second, your IDE may not able to show its actual value while maintaining semantic meaning.

Enum, on the other hand, has semantic meaning, can be easily defined without typing much. Also its type is checked by compiler. This is pretty important. However, enum is only confined to integer type. Enum also works with old C compilers.

const global variable is quite general. Its type is checked, can maintain sematic meaning, and can be any type freely. This is quite a good option for C++ or new C compilers.

When a couple of values are to be defined, enum is the most covenient. So, I use it usually, but sometimes use const global variable.

What do you think about this?

2 responses to this post.

  1. There are pros and cons to each approach and you did a fair job at enumerating them. One thing missing about #defines is there’s lots of magic and voodoo you can do via the preprocessor that can make #defines worthwhile. Nevertheless, the fact it’s difficult to typecheck can lead to lots of errors so generally using something like an enum tends to be a better way to go, especially if you typedef the enum into a unique type.

    Reply

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: