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.
Consider this code,
Obviously each multiplication results in compilation-error, but see how the GCC generates the messages for each multiplication error:
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 seeWIDTH
, all it sees only 300, as before GCC compiles the line, preprocessor has already replacedWIDTH
with 300. On the other hand, there is no any such thing happens with enumeWidth
and constWidth
.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.The compiler stores enum information in the binary when the program is compiled with certain options.
When a variable is of a enum type, a debugger can show the enum name. This is best shown with an example:
If you compile that with
gcc -g
you can try out the following ingdb
:If you used a define, you would not have a proper type to give
e
, and would have to use an integer. In that case, the compiler would print1
instead ofONE_E
.The
-g
flag asks gdb to add debugging information to the binary. You can even see that it is there by issuing:I don't think that this will work in all architectures, though.
I am answering too late but i feel i can add something - enum vs. const vs. #define
enum -
You can have a variable of enum type to which you can assign an enum
typedef enum numbers { DFAULT, CASE_TRUE, CASE_OTHER, };
int main(void) { numbers number = CASE_TRUE; }
const -
defines are pre-processing directive but const is compile time for example
const char *name = "vikas";
You can access the name and use its base address to read the such as vikas[3] to read 'a' etc.
#defines - are dumb preprocessor directives which does textual replacement
At least for Visual Studio 2008 which I currently have at hand, this sentence is correct. If you have
and you set a breakpont in
main
, you can hover your mouse over "MyX" and see that it evaluates to 3. You do not see anything useful if you hover over X.But this is not a language property but rather IDE behavior. Next versions might do it differently, as well as others IDEs. So just check it out for your IDE to see if this sentence applies in your case.
Check the following article, nice summary http://www.queryhome.com/26340/define-vs-enum-vs-constant
enum
is compile time constant with debug info with no storage allocation.const
is allocated with a storage, depending on whether it is optimised away by the compiler with constant propagation.#define
has no storage allocation.