Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Enum and Define Statements

What's the difference between using a define statement and an enum statement in C/C++ (and is there any difference when using them with either C or C++)?

For example, when should one use

enum {BUFFER = 1234};  

over

#define BUFFER 1234    
like image 468
Zain Rizvi Avatar asked Sep 25 '08 23:09

Zain Rizvi


People also ask

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 difference between #define and typedef?

typedef is limited to giving symbolic names to types only, whereas #define can be used to define an alias for values as well, e.g., you can define 1 as ONE, 3.14 as PI, etc. typedef interpretation is performed by the compiler where #define statements are performed by preprocessor.

What is the difference between an enumeration and a set of preprocessor #defines?

enum is a keyword. It is an Enumerator by which you can create and define your own data type. #define is a pre-processor command that substitutes a character sequence for the identifier each time it is encountered. It will substitute 100 everywhere you've written Max.

What is the difference between enum and macro?

One difference is that macros allow you to control the integral type of related constants. But an enum will use an int . In C, enum constants are always int , there is no such rule about wider types.


2 Answers

enum defines a syntactical element.

#define is a pre-preprocessor directive, executed before the compiler sees the code, and therefore is not a language element of C itself.

Generally enums are preferred as they are type-safe and more easily discoverable. Defines are harder to locate and can have complex behavior, for example one piece of code can redefine a #define made by another. This can be hard to track down.

like image 54
Jason Cohen Avatar answered Sep 19 '22 10:09

Jason Cohen


#define statements are handled by the pre-processor before the compiler gets to see the code so it's basically a text substitution (it's actually a little more intelligent with the use of parameters and such).

Enumerations are part of the C language itself and have the following advantages.

1/ They may have type and the compiler can type-check them.

2/ Since they are available to the compiler, symbol information on them can be passed through to the debugger, making debugging easier.

like image 25
paxdiablo Avatar answered Sep 21 '22 10:09

paxdiablo