473,722 Members | 2,161 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Const vars vs. defines

Hi,

I saw this code in an earlier post
(not that there's anything wrong with it)

#include <iostream>
using std::cout;

const int hour = 3600;
const int min = 60;

class Time
{
int m_t; // member seconds
public:
Time(int t) : m_t(t)
{
...
What's up with Cpp-stuff like this?
What's so much more practical with consts vs. #defines?
It uses unnecessary space, and the typical use (at least for me)
are _simple_ constants like SCREEN_WRES, SECS_IN_HOUR, etc.

Yes, there are issues when formatting, data types, etc. can
can get nasty with defines, but do professional programmers like _you_
ever have problems with defines?
I'm actually wondering.

-- Pelle
Jul 23 '05 #1
4 1639
"Pelle Beckman" <he******@chell o.se> wrote in message
news:tpK6e.769$ 184.193@amstwis t00
Hi,

I saw this code in an earlier post
(not that there's anything wrong with it)

#include <iostream>
using std::cout;

const int hour = 3600;
const int min = 60;

class Time
{
int m_t; // member seconds
public:
Time(int t) : m_t(t)
{
...
What's up with Cpp-stuff like this?
What's so much more practical with consts vs. #defines?
It uses unnecessary space, and the typical use (at least for me)
are _simple_ constants like SCREEN_WRES, SECS_IN_HOUR, etc.

Yes, there are issues when formatting, data types, etc. can
can get nasty with defines, but do professional programmers like _you_
ever have problems with defines?
I'm actually wondering.

-- Pelle

One advantage of the const int version is that it respects scopes. #defines
don't.
--
John Carson

Jul 23 '05 #2
John Carson skrev:
"Pelle Beckman" <he******@chell o.se> wrote in message
news:tpK6e.769$ 184.193@amstwis t00
Hi,

I saw this code in an earlier post
(not that there's anything wrong with it)

#include <iostream>
using std::cout;

const int hour = 3600;
const int min = 60;

class Time
{
int m_t; // member seconds
public:
Time(int t) : m_t(t)
{
...
What's up with Cpp-stuff like this?
What's so much more practical with consts vs. #defines?
It uses unnecessary space, and the typical use (at least for me)
are _simple_ constants like SCREEN_WRES, SECS_IN_HOUR, etc.

Yes, there are issues when formatting, data types, etc. can
can get nasty with defines, but do professional programmers like _you_
ever have problems with defines?
I'm actually wondering.

-- Pelle


One advantage of the const int version is that it respects scopes.
#defines don't.

true, and very smart.
I've never thought of that.
Jul 23 '05 #3
John Carson wrote:
Yes, there are issues when formatting, data types, etc. can
can get nasty with defines, but do professional programmers like _you_
ever have problems with defines?
I'm actually wondering.

-- Pelle


One advantage of the const int version is that it respects scopes. #defines
don't.


Another thing is that may debugger knows about the constants because they
are ordinary constant variabels. However my debugger knows nothing
about macros.
--
Karl Heinz Buchegger
kb******@gascad .at
Jul 23 '05 #4
On Tue, 12 Apr 2005 09:03:52 +0200, Pelle Beckman <he******@chell o.se>
wrote:
Hi,
Hello.
[...]What's so much more practical with consts vs. #defines?
It uses unnecessary space, and the typical use (at least for me)
are _simple_ constants like SCREEN_WRES, SECS_IN_HOUR, etc.

You're question is restricted to simple types, so we don't need to
bring const aggregate types into this.

Compilers can optimize out 'const' variables by replacing them with
their value, which removes the need to store the value in any object
file. A stripped binary will incur no penalty for the use of a const
over a macro in the source. A variable which has been optimized out
in this manner may no longer be visible to a debugger; at the very
least, its value won't, but the value can be determined by inspecting
the source (see difference 2 below for more on this).

Even without the optimization, the space penalty for simple constants
is negligible, unless you're working on an embedded system. Even with
64 bit ints, 128 const ints will only consume 1 KB to store their
values.

Most differences between the two is the result of the fact that const
variables respect C++ syntax and semantics while macros ignore it
(both John Carson's point about scopes and the points below are
consequences of this). For example,

1) const variables have an implicit type; macro names do not (though a
macro's value may have a type). Whether that works for you or against
you depends on context.

2) Macros can cause problems with or reduce the efficacy of various
programming tools, including documentation generators and other
literate programming tools, cross reference tools and syntax checkers.
Karl Heinz Buchegger already mentioned debuggers.

2) This point is more about the problems of #undef than macro
constants. If you've seen a macro defined in one place and used
somewhere else, and the locations are in different files or there are
intervening includes, you can't really know the value of the macro
when used. If you see the definition of a const variable and see it
used somewhere else, you can be almost certain of its value. This is
because you can only cast away the const-ness of pointers and
references, which means more hoops to jump through to assign to a
non-pointer and non-ref const, whereas you can easily undefine and
redefine a macro. Redefining a macro will never be a problem if all
programmers involved are perfect, but in all other cases is a
potential source of bugs. If i is a global const int,
"*(const_cast<i nt*>(&i))=1" will compile but you may get a segfault
when the assignment is executed. Redefining a macro is more likely to
compile and run without obvious errors, but you may get unexpected and
hard to debug behavior. Whether any of that works for you or against
you depends on context.

Kanenas
Jul 23 '05 #5

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

Similar topics

19
2799
by: Christian Engström | last post by:
If you have a function that returns something by value, the gcc compiler (version 3.2.3 on Windows XP with MinGW) converts the returned value from the type you specify in the code, to the const version of that type. Is this a bug that is specific to gcc, or is it a flaw in the language specification that gcc diligently implements? For example, the below program produces the output Constant Mutable
11
2554
by: Andy White | last post by:
What is preferable to use for constants, #defines or const identifiers. And where is it customary to place const indentifiers in your files? thanks.
7
4360
by: al | last post by:
char s = "This string literal"; or char *s= "This string literal"; Both define a string literal. Both suppose to be read-only and not to be modified according to Standard. And both have type of "const char *". Right? But why does the compiler I am using allow s to be modified, instead of generating compile error?
16
12302
by: Peter Ammon | last post by:
Often times, I'll have some malloc()'d data in a struct that need not change throughout the lifetime of the instance of the struct. Therefore, the field within the struct is declared a pointer to const . But then free() complains when I pass in the pointer because free() is declared as void free(void*). So I have to cast. Why is it not declared as void free(const void*), which would save me these headaches? -Peter
4
3303
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 time, and inline functions are all defined in headers. " Can someone explain to me why some of the const objects must be defined in the header file?
2
7997
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
2
2249
by: Adrian | last post by:
Hi, In a header file I tried const char *someval="this is a test"; which is included all over the place and I get linker errors about multiple defines. Why is this not folded when const char someval="this is a test"; is and I get no linker errors?
2
1315
by: Poofactory | last post by:
HI, I have a control on a content page that I need to access and modify a MasterPage variable. I can find the control alright: if (Parent.Page.Master.FindControl("Adserver_TopBanner1") != null) {
7
1928
by: Luna Moon | last post by:
Hi all, I just couldn't get myself clear about the usage of "const" in front of and/or behind variables, pointers, classes, objects and functions... It's too confusing... any good clear article/tutorial that can help me? Thanks a lot!
0
9238
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9088
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8052
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5995
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4502
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4762
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3207
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2602
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2147
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.