473,587 Members | 2,321 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

#define vs. const

Greetings everyone,

I was wondering if a const variable or object took up space. I know
that a #define'd macro doesn't, as it's basically just interpreted by
the compiler. If a const does take up space, is there any reason to
choose it over a #define'd constant?

-- Thank you

P.S. if it makes any difference, I ssh to a SunOs machine where I use
g++ as my compiler.
Jul 22 '05 #1
19 16285
In article <Xn************ ********@216.77 .188.18>,
Robert <gr*****@REMOVE hotmail.com> wrote:
I was wondering if a const variable or object took up space.
It might, or it might not. Generally speaking, usually a scalar
integeral need not take up space if their address is not taken.
Hence, the classic situation of somehting such as:

const int buf = 99;

char a[buf];

int main()
{
return 0;
}

Here, buf can be used to obtain the constant expression necessary
for the array dimension, and at the same time, the compiler probably
won't both to allocate any runtime space for it since it isn't
otherwise used. It can get slippery though. And there are
cases where compilers normally wouldn't do it:

const double d = 1234.4321;
const int array[999]; // int, but probably still allocated.

Of course, all this is notwithstanding program optimizations
that are allowed to occur.
I know
that a #define'd macro doesn't, as it's basically just interpreted by
the compiler. If a const does take up space, is there any reason to
choose it over a #define'd constant?


Check out http://www.comeaucomputing.com/techtalk/#definevsconst
for a higher level response, and not intended to be narrowminded
since as usual decisions should be context driven.
--
Greg Comeau / Comeau C++ 4.3.3, for C++03 core language support
Comeau C/C++ ONLINE ==> http://www.comeaucomputing.com/tryitout
World Class Compilers: Breathtaking C++, Amazing C99, Fabulous C90.
Comeau C/C++ with Dinkumware's Libraries... Have you tried it?
Jul 22 '05 #2
Robert wrote:
I was wondering if a const variable or object took up space.
You are probably confusing C with C++.
I know that a #define'd macro doesn't
as it's basically just interpreted by the compiler.
I don't think that you *know* any such thing.
cat f.cc #ifdef UH
#define constant 1024*1024
#else //UH
const int constant = 1024*1024;
#endif//UH

extern
void g(int);

void f(void) {
g(constant);
}
g++ -DUH -Wall -ansi -pedantic -O3 -S -o f.sold f.cc
g++ -Wall -ansi -pedantic -O3 -S -o f.snew f.cc
diff f.sold f.snew
My compiler emits *exactly* the same code
whether I use #define or const.
If a const does take up space,
is there any reason to choose it over a #define'd constant?


C preprocessor macro definitions are dangerous.
They don't respect local scope for example.
Jul 22 '05 #3
Robert posted:
Greetings everyone,

I was wondering if a const variable or object took up space. I know that a #define'd macro doesn't, as it's basically just interpreted by the compiler. If a const does take up space, is there any reason to choose it over a #define'd constant?

-- Thank you
P.S. if it makes any difference, I ssh to a SunOs machine where I use g++ as my compiler.

MACROS ARE EVIL

Don't use macros.

There's is absolutlely no need for them in C++.

Macro constants -> const global variables
Macro functions -> inline functions

If you use macros for any other reason, eg. to get some new
special syntax, then it's perverted.

Not only do macro "functions" not follow scoping rules, but
also when they're passed the likes of:

Func(++a, b+=6)

Then they may increment "a" more than once and add 6 to
"b" more than once too.

Also if you want a callback function out of a macro:

CallBack(Func)

Well, let's just say it doesn't work.

MACROS WILL DIE

-JKop
Jul 22 '05 #4
"JKop" <NU**@NULL.NULL > wrote in message
news:pK******** **********@news .indigo.ie...
MACROS ARE EVIL

Don't use macros.

There's is absolutlely no need for them in C++.

Macro constants -> const global variables
Macro functions -> inline functions
I agree that macros are evil, and that in most of their
current uses, they are best replaced as you suggested.
However, I wouldn't go as far as to say that there are
absolutely no need for them.
Include guards are usually based on macros, right?
If you use macros for any other reason, eg. to get some new
special syntax, then it's perverted. .... MACROS WILL DIE


Someday they may well be replaced by a better/safer mechanism.
So far, many find that there are still many legitimate uses
for them, and even developed supporting libraries.
For advanced examples see:
http://www.boost.org/libs/preprocessor/doc/index.html

At the language level itself, I wouldn't bet that new
extensions to the C preprocessor (e.g. variadic arguments)
won't be adopted in the next C++ standard.
Regards,
Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form

Jul 22 '05 #5
JKop wrote:
MACROS ARE EVIL

Don't use macros.

There's is absolutlely no need for them in C++.
Actually there are some uses with no other alternatives like #ifndef's.
But in general, they should be avoided.

Macro constants -> const global variables
Macro functions -> inline functions


and templates.

--
Ioannis Vranos

http://www23.brinkster.com/noicys
Jul 22 '05 #6
JKop wrote:
Robert posted:
Greetings everyone,

I was wondering if a const variable or object took up space. I know
that a #define'd macro doesn't, as it's basically just

interpreted by
the compiler. If a const does take up space, is there any

reason to
choose it over a #define'd constant?

--

Thank you

P.S. if it makes any difference, I ssh to a SunOs machine

where I use
g++ as my compiler.

MACROS ARE EVIL

Don't use macros.


That won't help without giving a reason.
There's is absolutlely no need for them in C++.

Macro constants -> const global variables
#ifndef FOO_H_INCLUDED
#define FOO_H_INCLUDED

//foo.h contents

#endif
Macro functions -> inline functions
#define ASSERT(x) \
if (!(x)) \
std::cerr << "Assert failure in line " << __LINE__ << std::endl;
If you use macros for any other reason, eg. to get some new
special syntax, then it's perverted.
That's your opinion.
Not only do macro "functions" not follow scoping rules, but
also when they're passed the likes of:

Func(++a, b+=6)

Then they may increment "a" more than once and add 6 to
"b" more than once too.
Even further, that may introduce undefined behaviour, like in the infamous
example:

#define MIN(x, y) ((x) < (y) ? (x) : (y))

//...
int a = 3;
int b = 5;
int c = MIN(a++, b--);
Also if you want a callback function out of a macro:

CallBack(Func)

Well, let's just say it doesn't work.


Macros also don't support namespaces and cannot be made members of classes.
Further, they are not type safe.

Jul 22 '05 #7

"JKop" <NU**@NULL.NULL > wrote in message
news:pK******** **********@news .indigo.ie...
[SNIP]

MACROS ARE EVIL

Don't use macros.

There's is absolutlely no need for them in C++.
Sit back and relax for a moment ;-) I totally agree that macros are evil but
the statement that there is absolutely no need for them in C++ is more than
arguable. There are a couple of situations that spring to my mind where they
come in very handy. Just think of include guards, or of some more nifty uses
like in compile time asserts with more informative error messages. I simply
don´t know how you´d achieve it without a macro.

template <bool x> struct StaticAssert {
StaticAssert(.. .);
};
template <> struct StaticAssert<fa lse>{};
#define COMPILE_ASSERT( Expr, Msg ) \
{ \
class ERROR_##Msg {}; \
(void)sizeof( StaticAssert<(E xpr) != 0>(( ERROR_##Msg())) ); \
}

Macro constants -> const global variables
Macro functions -> inline functions
Point taken and you´re absolutey right there.

If you use macros for any other reason, eg. to get some new
special syntax, then it's perverted.
[SNIP]
MACROS WILL DIE


Wait and see, probably they might be replaced by some safer mechanism.

Regards
Chris
Jul 22 '05 #8
Chris Theis wrote:
Sit back and relax for a moment ;-) I totally agree that macros are evil but
the statement that there is absolutely no need for them in C++ is more than
arguable. There are a couple of situations that spring to my mind where they
come in very handy. Just think of include guards,
In most compilers inclusion guards can be replaced with #pragma
directives. Like

#pragma once
or of some more nifty uses
like in compile time asserts with more informative error messages. I simply
don´t know how you´d achieve it without a macro.

template <bool x> struct StaticAssert {
StaticAssert(.. .);
};
template <> struct StaticAssert<fa lse>{};
#define COMPILE_ASSERT( Expr, Msg ) \
{ \
class ERROR_##Msg {}; \
(void)sizeof( StaticAssert<(E xpr) != 0>(( ERROR_##Msg())) ); \
}

With an array of pointers to functions or objects may be?

--
Ioannis Vranos

http://www23.brinkster.com/noicys
Jul 22 '05 #9
Thanks everyone for your replies. I've been searching around and saw
this article: http://www.embedded.com/story/OEG20011016S0116 . It
mentions something about const variables/objects receiving performance
penalties.

Jul 22 '05 #10

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

Similar topics

8
2548
by: John Ratliff | last post by:
Let's say I had a program which uses some constants. Would it be "better" to declare them like this: #ifndef __MY_HDR_FILE #define __MY_HDR_FILE #define STRING_CONST "some string..." #define INT_CONSTANT 4852 #endif
4
2244
by: Rayer | last post by:
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
2771
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 example: In version.h ------------ #ifndef VERSION #define VERSION
2
7985
by: Jason | last post by:
What is the difference between 'const' and 'define()' ? When would I prefer using 'const' over 'define', or vice versa? It seems if i do: const secondsInMinute = 60; define("secondsInMinute", 60); Aren't these two the same thing? - Jason
5
3219
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 #define with const. example: 2 header file StringGrid1.h StringGrid2.h
23
3894
by: anon.asdf | last post by:
Hello! In the following code-snippet, is it possible to initialize each element of arr, with STRUCT_INIT? struct mystruct { int a; char b; };
5
2565
by: alan | last post by:
Hello world, I'm wondering if it's possible to implement some sort of class/object that can perform mapping from class types to strings? I will know the class type at compile time, like so: const char *s = string_mapper<thetype>(); However I do not know the string to be associated with the type at compile time, and will need a way to set...
6
2142
by: wongjoekmeu | last post by:
I need to rewrite some typedef to #define. For instance I rewrote typedef void* handle to #define handle void* But I saw for instance another typedef in my code which I don't understand, which is
27
5395
by: pereges | last post by:
I need to define the plancks constant 6.67 X 10 exp -34. Is it possible to do it using #define or would you suggest using a (static ?)const double.
1
5212
by: sophia | last post by:
Dear all, the following are the differences b/w #define and typedef ,which i have seen in Peter van der lindens book. is there any other difference between thes two ? The right way to think about typedef as being a complete encapsulated type - you can't add to it after you have declared it.
0
7918
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
8340
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7967
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
8220
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
5392
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3840
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3875
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1452
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1185
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.