Why use enum when #define is just as efficient?


This question already has an answer here:


the advantages of enum show up when you have a long list of things you want to map into numbers, and you want to be able to insert something in the middle of that list. for example, you have:

pears 0
apples 1
oranges 2
grapes 3
peaches 4
apricots 5

now you want to put tangerines after oranges. with #defines, you'd have to redefine the numbers of grapes, peaches, and apricots. using enum, it would happen automatically. yes, this is a contrived example, but hopefully it gives you the idea.

I find it useful for debugging in an environment such as gdb since enum values are handled at compile time (where #define is a preprocessor macro) and thus available for introspection.

Although your question is tagged as C, there is a big advantage when writing in C++, you can place enum:s inside classes or namespaces. This way you could refer to your constants like 'SpaceshipClass::galaxy'.

enum is an integer constant. so, there would be a type check during compilation process.

Need Your Help

namespace naming conventions

c# .net namespaces design-guidelines

For those of you out there writing reusable components, what do you consider to be best practice if you're extending the functionality of the .NET framework?

Catching SQL Injection and other Malicious Web Requests

sql xss sql-injection

I am looking for a tool that can detect malicious requests (such as obvious SQL injection gets or posts) and will immediately ban the IP address of the requester/add to a blacklist. I am aware that...