473,320 Members | 1,699 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Const vs # Define in the header file

Hi All C++ Experts

(1)I want have a simple suggestion from u all experts
which is preferable const or #define and in which cases

(2)in my project i want to avoid hardcoding , for that
i have defined macros in my header files. but we have coding
rules that says "use const for avoiding hardcoding".My question is
that "what will be the difference in terms of memory for Const vs #
Define"

Thanks and regards
Raj

Jul 23 '05 #1
14 10330
Rajan wrote:
Hi All C++ Experts

(1)I want have a simple suggestion from u all experts
which is preferable const or #define and in which cases

(2)in my project i want to avoid hardcoding , for that
i have defined macros in my header files. but we have coding
rules that says "use const for avoiding hardcoding".My question is
that "what will be the difference in terms of memory for Const vs #
Define"


I will suggest that const is better when using debuggers because you can
see the value of of consts where as I believe this is not the case for
#define.
Jul 23 '05 #2
"Rajan" <Sh**************@gmail.com> wrote in message
news:11**********************@l41g2000cwc.googlegr oups.com...
Hi All C++ Experts

(1)I want have a simple suggestion from u all experts
which is preferable const or #define and in which cases
const. All cases.
(2)in my project i want to avoid hardcoding , for that
i have defined macros in my header files. but we have coding
rules that says "use const for avoiding hardcoding".My question is
that "what will be the difference in terms of memory for Const vs #
Define"


That's up to the compiler, but I can't see any reason why a good compiler
should do const values any less efficiently than #define.

#define is horrible. It's processed by the pre-processor, not by the C++
compiler proper. The preprocessor does nothing but text replacement, so
#defines have no respect for the usual C++ scoping rules. They are ghastly,
and I can't think of a single reason why you'd use a #define where a const
can be used.

DW
Jul 23 '05 #3
On 5 Apr 2005 23:30:41 -0700, Rajan <Sh**************@gmail.com> wrote:

[...]
(1)I want have a simple suggestion from u all experts
which is preferable const or #define and in which cases
modern c++ style never uses #define for constant values used in c++ code
(this is what all the gurus say, afaik: sutter, myers, alexandrescu, ...)
there may be _very_ rare exceptions.

(2)in my project i want to avoid hardcoding , for that
i have defined macros in my header files. but we have coding
rules that says "use const for avoiding hardcoding".My question is
that "what will be the difference in terms of memory for Const vs #
Define"


well, if you have
const int A = 10;
it will occupy sizeof(int) bytes of memory as long as it lives.

on the other hand, if you have
#define A 10
the _preprocessor_ will literally replace every "A" in your source code by
"10", so this #defined a uses no memory. however, those variables holding
the value A use memory, off course.

remark:
to really avaoid hardcoding of constants (my point of view is that
"hardcoded" is anything the change of which requires a re-compilation),
your program should use an initialisation file. then, the name of this
file is the only thing which needs to be hardcoded.

or even better: pass that name as (the only) command line parameter, or
read it from the registry. then your program will be totally free of
hardcoding.
Jul 23 '05 #4
Always use const, among various reasons, it has scope and has a type, while
a #define has none of those.

In terms of memory, it should be the same thing, I would assume.

Hope that helps,
George Faraj
"Rajan" <Sh**************@gmail.com> wrote in message
news:11**********************@l41g2000cwc.googlegr oups.com...
Hi All C++ Experts

(1)I want have a simple suggestion from u all experts
which is preferable const or #define and in which cases

(2)in my project i want to avoid hardcoding , for that
i have defined macros in my header files. but we have coding
rules that says "use const for avoiding hardcoding".My question is
that "what will be the difference in terms of memory for Const vs #
Define"

Thanks and regards
Raj

Jul 23 '05 #5
ulrich, the compiler can optimize and I think it should be the same
memory usage as using a define.

Jul 23 '05 #6
* Rajan:

(1)[...] which is preferable const or #define and in which cases
'const' is used to define typed constants.

'#define' is used to define macros.
(2)in my project i want to avoid hardcoding , for that
i have defined macros in my header files.
"hardcoding" refers to maintainability, which is a good idea to focus on.

Macros generally lower maintainability.

What you're doing does not make sense in terms of the stated goal.

but we have coding
rules that says "use const for avoiding hardcoding".My question is
that "what will be the difference in terms of memory for Const vs #
Define"


"memory usage" refers to some kind of misguided premature optimization, which
is a really bad idea to focus on.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jul 23 '05 #7
"ulrich" <ua********@aon.at> wrote in message
news:opsoswgqxan2mgp5@innsbruck-neu...
On 5 Apr 2005 23:30:41 -0700, Rajan <Sh**************@gmail.com> wrote:
well, if you have
const int A = 10;
it will occupy sizeof(int) bytes of memory as long as it lives.
I doubt it, at least for processors that can more efficiently embed
hard-wired immediate values in code than fetch a value from memory.
Examples:
------------
#define A 10

void f(int);

void g()
{
f(A);
}

x86 code generated for g() by VC++ 6.0:
push 10
call f
add esp, 4
------------
const int A = 10;

void f(int);

void g()
{
f(A);
}

x86 code generated for g() by VC++ 6.0:
push 10
call f
add esp, 4
------------
on the other hand, if you have
#define A 10
the _preprocessor_ will literally replace every "A" in your source code by
"10", so this #defined a uses no memory. however, those variables holding
the value A use memory, off course.

remark:
to really avaoid hardcoding of constants (my point of view is that
"hardcoded" is anything the change of which requires a re-compilation),
your program should use an initialisation file. then, the name of this
file is the only thing which needs to be hardcoded.

or even better: pass that name as (the only) command line parameter, or
read it from the registry. then your program will be totally free of
hardcoding.


DW

Jul 23 '05 #8
ulrich wrote:
well, if you have
const int A = 10;
it will occupy sizeof(int) bytes of memory as long as it lives.
It might, or it might not. Depends on the compiler.
on the other hand, if you have
#define A 10
the _preprocessor_ will literally replace every "A" in your source code by
"10", so this #defined a uses no memory.
Might also be just the other way round.
however, those variables holding the value A use memory, off course.
Well, it depends. Some CPUs will insert the value directly into the code
that loads that value into the register. If it has to be loaded from
memory, the memory address needs to be provided in the code instead.
OTOH, some CPUs cannot directly write the value 10 into a register. They
need to read it from some memory location, in which case the #define might
result in an extra memory use for every occurance of A, while the const
would need only one.
Of course that all depends on the capabilities of the compiler and on the
platform. But even if you have the case of the #define needing no memory
and the const needing it, then sizeof(int) isn't a big deal unless you're
on a very limited embedded platform. E.g. on a 32bit platform, sizeof(int)
is usually 4. With 512MB of memory, 4 bytes are about 7e-7 percent of the
total memory.
remark:
to really avaoid hardcoding of constants (my point of view is that
"hardcoded" is anything the change of which requires a re-compilation),
Though I agree here, it seems the OP rather meant avoiding magic numbers
within the code and replacing them with a constant or a #define to
centralize it and to document its meaning through giving it a proper name.
your program should use an initialisation file. then, the name of this
file is the only thing which needs to be hardcoded.


That depends on the purpose of the value. For example, there is no need to
have the following replaced by a configuration file entry:

const int hours_per_day = 24;

because the number of hours per day is not expected to change, and it would
clutter the config file with useless options.

Jul 23 '05 #9
On Wed, 6 Apr 2005 20:05:07 +1000, David White <no@email.provided> wrote:
"ulrich" <ua********@aon.at> wrote in message
news:opsoswgqxan2mgp5@innsbruck-neu...
On 5 Apr 2005 23:30:41 -0700, Rajan <Sh**************@gmail.com> wrote:
well, if you have
const int A = 10;
it will occupy sizeof(int) bytes of memory as long as it lives.


I doubt it, at least for processors that can more efficiently embed
hard-wired immediate values in code than fetch a value from memory.
Examples:
------------
#define A 10

void f(int);

void g()
{
f(A);
}

x86 code generated for g() by VC++ 6.0:
push 10
call f
add esp, 4
------------
const int A = 10;

void f(int);

void g()
{
f(A);
}

x86 code generated for g() by VC++ 6.0:
push 10
call f
add esp, 4
------------


ok, however this translation of the compiler is not c++ business ;-)
Jul 23 '05 #10

"Rolf Magnus" <ra******@t-online.de> schrieb im Newsbeitrag
news:d3*************@news.t-online.com...
[SNIP]
That depends on the purpose of the value. For example, there is no need to
have the following replaced by a configuration file entry:

const int hours_per_day = 24;

because the number of hours per day is not expected to change, and it would clutter the config file with useless options.


....and will certainly lead to funny behavior one day. Imagine a user
changing the hours_per_day value to 20 ;-) IMO there are some things that
should be kept away from the user's (probably subconscious) fiddling.

Cheers
Chris
Jul 23 '05 #11

"Rajan" <Sh**************@gmail.com> wrote in message
news:11**********************@l41g2000cwc.googlegr oups.com...
Hi All C++ Experts

(1)I want have a simple suggestion from u all experts
which is preferable const or #define and in which cases

This issue is covered by the FAQ:
http://www.parashift.com/c++-faq-lit....html#faq-29.7
Regards,
Sumit.
--
Sumit Rajan <su*********@gmail.com>
Jul 23 '05 #12
Sumit Rajan wrote:
Rajan wrote:
(1)I want have a simple suggestion from all of you experts.
Which is preferable? const? Or #define?


This issue is covered by the FAQ:
http://www.parashift.com/c++-faq-lit....html#faq-29.7


I think that this FAQ covers Rajan's question adequately.
Jul 23 '05 #13

"ulrich" <ua********@aon.at> skrev i en meddelelse
news:opsos6a0drn2mgp5@innsbruck-neu...
On Wed, 6 Apr 2005 20:05:07 +1000, David White <no@email.provided> wrote:
"ulrich" <ua********@aon.at> wrote in message
news:opsoswgqxan2mgp5@innsbruck-neu...
On 5 Apr 2005 23:30:41 -0700, Rajan <Sh**************@gmail.com> wrote:
well, if you have
const int A = 10;
it will occupy sizeof(int) bytes of memory as long as it lives.


I doubt it, at least for processors that can more efficiently embed
hard-wired immediate values in code than fetch a value from memory.
Examples:
------------
#define A 10

void f(int);

void g()
{
f(A);
}

x86 code generated for g() by VC++ 6.0:
push 10
call f
add esp, 4
------------
const int A = 10;

void f(int);

void g()
{
f(A);
}

x86 code generated for g() by VC++ 6.0:
push 10
call f
add esp, 4
------------


ok, however this translation of the compiler is not c++ business ;-)


What do you mean by that? This translation is perfectly legal C++.

/Peter
Jul 23 '05 #14
"Peter Koch Larsen" <pk*****@mailme.dk> wrote in message
news:at*********************@news000.worldonline.d k...

"ulrich" <ua********@aon.at> skrev i en meddelelse
news:opsos6a0drn2mgp5@innsbruck-neu...
On Wed, 6 Apr 2005 20:05:07 +1000, David White <no@email.provided> wrote:
x86 code generated for g() by VC++ 6.0:
push 10
call f
add esp, 4
------------
const int A = 10;

void f(int);

void g()
{
f(A);
}

x86 code generated for g() by VC++ 6.0:
push 10
call f
add esp, 4
------------


ok, however this translation of the compiler is not c++ business ;-)


What do you mean by that? This translation is perfectly legal C++.


The source code is perfectly legal C++, but the translation to assembly
isn't. However, if the assembly isn't C++ business, neither was the
statement that a const int occupies szieof(int) bytes of memory, because
that's as compiler-specific as the assembly, and that was what I was
challenging.

DW


Jul 23 '05 #15

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
by: Mathieu Malaterre | last post by:
Hello, This thread follow my previous one on the gcc mailing list. Basically I -still- have a problem in my code. I define in a header file: static const std::string foo = "bar"; Which not...
15
by: Dave | last post by:
Hello NG, It is well known that memory-allocating definitions should not be put in a header file. I believe, however, that this does not apply to const definitions. For example: #ifndef...
12
by: Riley DeWiley | last post by:
I am looking for a graceful way to declare a string const that is to be visible across many files. If I do this: //----hdr.h const char * sFoo = "foo"; //file.cpp
13
by: Amadeus W. M. | last post by:
I have a member static const int x defined in class Foo, and I'm passing it by reference, and by value elsewhere (see the code below). Passing it by value works, but by reference it doesn't: it...
3
by: S Austin | last post by:
I would like to define a structure (a file header, in this case) that includes certain constants, and ensure that those members of the structure are always initialized to the same value. ...
4
by: yancheng.cheok | last post by:
Recently, I try to replace #define with const in header file. However, there are concerns on, multiple const object will be created, if the header file is included in multiple cpp files. For...
4
by: Rui.Hu719 | last post by:
Hi, All: I read the following passage from a book: "There are three exceptions to the rule that headers should not contain definitions: classes, const objects whose value is known at compile...
5
by: MoslyChang | last post by:
Hi, All When I look at effective c++,item2 and item3. I have some basic questions , Does anyone be familar with this topic? it suggests const is perfer to #define, then I think how to replace...
3
by: Kermit Mei | last post by:
Hello all, I wrote four simple c++ source files for this test. Look please: /*************1***************/ /// file A.h #ifndef A_H #define A_H class A { public: void set(int i);
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.