#define versus const

M

Mike Smith

johny said:
I have never really understood the difference between

1.) #define NUMBER 1.653

vs.

2.) const double NUMBER = 1.653

I know that the #define is taken care of by the pre-processor and the
compiler is used in the second case but why would one be chosen over the
other.

One book I read suggested that your should prefer the compiler to the
preprocessor, but why does it really matter?

Here's another reason in addition to those already given:

#define MACRO 1.653

const double CONST = 1.653;

double Square(double const *p)
{
return (*p) * (*p);
}

int main()
{
double a = Square(&MACRO); // won't compile

double b = Square(&CONST); // compiles OK

return 0;
}
 
T

Tim Slattery

Mike Smith said:
Here's another reason in addition to those already given:

#define MACRO 1.653

const double CONST = 1.653;

double Square(double const *p)
{
return (*p) * (*p);
}

int main()
{
double a = Square(&MACRO); // won't compile

Certainly not! After the preprocessor finishes with this line it look
like this:

double a = Square(&1.653);

which is meaningless.
double b = Square(&CONST); // compiles OK

CONST is a variable, not a macro, so the preprocessor does nothing to
this line.
 
K

Karl Heinz Buchegger

Tim said:
Certainly not! After the preprocessor finishes with this line it look
like this:

double a = Square(&1.653);

which is meaningless.

Didn't the comment in this line say: won't compile ?
CONST is a variable, not a macro, so the preprocessor does nothing to
this line.

And that's why Mike marked this line as : compiles OK
 
D

Dave Moore

JKop said:
JKop posted:
Luther Baker posted:
JKop wrote:

I'm in Ireland, (and we call them brackets).


Hi JKop,

Curious, what do you call the squared *thingies* in Ireland?

[ ]

-Luther

( ) Brackets

[ ] Square brackets / Block brackets

{ } Chain brackets


Sin a nglaonn muid orthu in Éirinn!


-JKop


As for:

< >


They're not used very much. We'd probably called them Arrow brackets or V
brackets.
How about angle brackets? <g>

Dave Moore
 
M

Mike Smith

Karl said:
Didn't the comment in this line say: won't compile ?




And that's why Mike marked this line as : compiles OK

I suppose I should simply have said that a const object is an object,
and can be treated like one, whereas a literal substitution cannot. <sigh>
 

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

Forum statistics

Threads
473,796
Messages
2,569,645
Members
45,368
Latest member
EwanMacvit

Latest Threads

Top