Is it really necessery to replace #define from const?

R

Rayer

I have got some project src, and find it out that there is no ppl using
"const" to define a constance, but using #define still more. Discussing
with my friend, he said 1. #define is much easier in modify values in
program for several propose, and 2. const takes memory but #define not.
However, most modern textbook (for example, C++ Primal Plus 4/e) still
suggest to use const to replace #define. I know that use #define will
have some problem when using as macro, but that affairs to function, not
const defination. anyone have idea why using const instead of using
#define ? any advantage?
 
I

Igor Okulist

"Compiler may optimize", I am afraid may is the keyword...
quite often does not, especially for globals (like PI).

That being said, majority still should use const.

igor
 
M

msalters

Rayer said:
I have got some project src, and find it out that there is no ppl using
"const" to define a constance, but using #define still more. Discussing
with my friend, he said 1. #define is much easier in modify values in
program for several propose,

Eh? That doesn't make sense in English. I can't guess what it means
so it's hard to reply.
and 2. const takes memory but #define not.

Wrong. Both take memory if needed, the compiler can optimize the
memory in both cases if not needed.
Of course, it is possible to take the address of a const, which
means the const will take memory. That's just an extra feature.
However, most modern textbook (for example, C++ Primal Plus 4/e) still
suggest to use const to replace #define. I know that using #define will
have some problem when using as macro, but that applies to function, not
const defination. anyone have idea why using const instead of using
#define ? any advantage?

Sure. E.g. a const has a type. i.e. const std::string foo = "X";
#define FOO "X" doesn't. The result is that passing foo to
void bar( std::string const& ) is cheaper. Every time you call
bar(FOO) the compiler has to convert FOO to a string, foo is
converted only once.

Overloading is more obvious, as it too works on types. Function
templates that deduce types are also affected, even those as
simple as std::find()

Furthermore, you can have consts in functions, and they will obey
function scope. A #define continues for the rest of the file.

Basically, C++ was designed with const in mind. #define was
accepted in C++ only to keep old C code working, and it
doesn't play nice with the new features.

HTH,
Michiel Salters
 

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,768
Messages
2,569,575
Members
45,053
Latest member
billing-software

Latest Threads

Top