Difference between enum and #define preprocessor

A

ashwani

Hi
Can any one tell me the difference between preprocessor macros like
#define and enum.
If i want to define MAX_LIMIT=100 as preprocessor macro as
#define MAX_LIMIT 100
or if i define enum {MAX_LIMIT=100}; then what is the basic difference?
Is there any efficiency tradeoff between both the definitions.
 
I

Ivan Vecerina

: Hi
: Can any one tell me the difference between preprocessor macros like
: #define and enum.
: If i want to define MAX_LIMIT=100 as preprocessor macro as
: #define MAX_LIMIT 100
: or if i define enum {MAX_LIMIT=100}; then what is the basic difference?
: Is there any efficiency tradeoff between both the definitions.

No difference in efficiency.

enum-declared constants are to be preferred because they
obey scoping rules (e.g. they can be encapsulated within
a class or namespace).

In a modern compiler, using
const int MAX_LIMIT = 100;
or
static const int MAX_LIMIT = 100;
is also likely to be just as efficient (no space or time
overhead) as a define.
 
R

Rolf Magnus

ashwani said:
Hi
Can any one tell me the difference between preprocessor macros like
#define and enum.
If i want to define MAX_LIMIT=100 as preprocessor macro as
#define MAX_LIMIT 100
or if i define enum {MAX_LIMIT=100}; then what is the basic difference?

enum respects scope, #define doesn't.
Is there any efficiency tradeoff between both the definitions.

no.

Btw: If you want a constant, just define a constant and not a macro or an
enum.
 
F

Frederick Gotham

ashwani posted:
Hi
Can any one tell me the difference between preprocessor macros like
#define and enum.
If i want to define MAX_LIMIT=100 as preprocessor macro as
#define MAX_LIMIT 100
or if i define enum {MAX_LIMIT=100}; then what is the basic difference?
Is there any efficiency tradeoff between both the definitions.


namespace MyNamespace {

#define ONE 1

enum { TWO = 2 };

int const three = 3;
}

int main()
{
ONE; /* No problem */

TWO; /* Can't find it */

three; /* Can't find it */


MyNamespace::ONE; /* Gibberish! */

MyNamespace::TWO; /* No problem */

MyNamespace::three; /* No problem */
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,955
Messages
2,570,117
Members
46,705
Latest member
v_darius

Latest Threads

Top