top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

    Get Free Article Updates

Facebook Login
Site Registration

Define vs Enum vs Constant

+13 votes
1,177 views

This is a classical issue with C and C++ probably with other language also. Which one best i.e. to use #define or enum or constant.

Lets analyse all three under the following point:

Debug-ability
1. #define values are replaced by the pre-processor with the value they are declared as, so in the debugger, it only sees the value, not the #defined name
2. The compiler stores enum information in the binary so a debugger can show the enum name
3. const is allocated with a storage so can be accessed by the deugger.

Memory Use
1. #define has no storage allocation.as it is pre-processor action
2. enum is compile time constant with no storage allocation.
3. const is allocated with a storage (depending on whether it is optimized away by the compiler with constant propagation)

Misc
1. enum and const respects scope and is type-safe.
2. a const variable can not be used as a dimension of an array where as enum and #define can be used. (C99 is exception)
3. If you need to pass a pointer you can use only const.
4. switch can work with enum or #define but not with const.

So in summary it is context dependent whether to use const or enum or #define. I just tried to summarize my learning, comments are welcome.

posted Dec 29, 2013 by Luv Kumar

  Promote This Article
Facebook Share Button Twitter Share Button LinkedIn Share Button

Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Bangalore-560102
Karnataka INDIA.
QUERY HOME
...