Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - enum vs. const vs. #define

At the end of the article here: http://www.learncpp.com/cpp-tutorial/45-enumerated-types/, it mentions the following:

Finally, as with constant variables, enumerated types show up in the debugger, making them more useful than #defined values in this regard.

How is the bold sentence above achieved?

Thanks.

like image 358
Simplicity Avatar asked Jan 22 '11 11:01

Simplicity


People also ask

Which is better const or enum?

Enums limit you to the required set of inputs whereas even if you use constant strings you still can use other String not part of your logic. This helps you to not make a mistake, to enter something out of the domain, while entering data and also improves the program readability.

What is the difference between enum and constant in C?

No, enum is a type that defines named values, a constant variable or value can be any type. You use an enum variable to hold a value of the enum type, you use a const to define a variable that cannot change and whose value is known at compile time.

Which is better #define or enum?

The use of an enumeration constant (enum) has many advantages over using the traditional symbolic constant style of #define. These advantages include a lower maintenance requirement, improved program readability, and better debugging capability.

What is the difference between enums and constants?

The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden). An enum cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces).


1 Answers

Consider this code,

#define WIDTH 300  enum econst {    eWidth=300 };  const int Width=300;  struct sample{};  int main()  {         sample s;         int x = eWidth * s; //error 1         int y = WIDTH * s;  //error 2         int z = Width * s;  //error 3         return 0; } 

Obviously each multiplication results in compilation-error, but see how the GCC generates the messages for each multiplication error:

prog.cpp:19: error: no match for ‘operator*’ in ‘eWidth * s’
prog.cpp:20: error: no match for ‘operator*’ in ‘300 * s’
prog.cpp:21: error: no match for ‘operator*’ in ‘Width * s’

In the error message, you don't see the macro WIDTH which you've #defined, right? That is because by the time GCC makes any attempt to compile the line corresponds to second error, it doesn't see WIDTH, all it sees only 300, as before GCC compiles the line, preprocessor has already replaced WIDTH with 300. On the other hand, there is no any such thing happens with enum eWidth and const Width.

See the error yourself here : http://www.ideone.com/naZ3P


Also, read Item 2 : Prefer consts, enums, and inlines to #defines from Effective C++ by Scott Meyers.

like image 183
Nawaz Avatar answered Oct 13 '22 13:10

Nawaz