473,887 Members | 2,280 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

question on c++ constants?

Dear All,

I am always confused in using constants in multiple files.

For global constants, I got some clues from
http://msdn.microsoft.com/en-us/libr...2d(VS.80).aspx

So in header file writing: const double PI = 3.14;
Every time using it, include the header file.

But how about constants in namespaces and classes?

Thanks for your help!

Shuisheng
Oct 14 '08 #1
54 3643
shuisheng wrote:
I am always confused in using constants in multiple files.

For global constants, I got some clues from
http://msdn.microsoft.com/en-us/libr...2d(VS.80).aspx

So in header file writing: const double PI = 3.14;
Every time using it, include the header file.

But how about constants in namespaces and classes?
Yes, we use them too. What's the problem?

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Oct 14 '08 #2
shuisheng wrote:
Dear All,

I am always confused in using constants in multiple files.

For global constants, I got some clues from
http://msdn.microsoft.com/en-us/libr...2d(VS.80).aspx

So in header file writing: const double PI = 3.14;
Every time using it, include the header file.

But how about constants in namespaces and classes?

Thanks for your help!

Shuisheng


1. The easiest constants in classes are made by using enums:
#include <vector>

class SomeClass
{
enum { SIZE= 7 };

int array[SIZE];

std::vector<int intVector;
public:
SomeClass(): intVector(5) {}
};

2. Regarding global constants and the header file you mentioned, in
simple words:

You can #include the header file with the global constant only in one
"implementation " file (e.g. .cpp) and to the rest implementation files
(e.g. .cpp), you can add the declaration:
extern const double PI;
==In general avoid objects in the global namespace.

3. Regarding constants in namespaces, you have to include the definition
in the implementation file (e.g. by placing it in the header file).
file1.cpp:
E.g. pi.h:

namespace SomeNamespace
{
const double PI = 3.14;
}


What should be preferred instead of constants in the global namespace:

Constants (consts/enums) in anonymous namespaces (= local file scope
only), and constants (consts/enums) in named namespaces.
Regarding classes, you can either use static constants or (usually
better) enums.
Oct 14 '08 #3
Corrected:

shuisheng wrote:
Dear All,

I am always confused in using constants in multiple files.

For global constants, I got some clues from
http://msdn.microsoft.com/en-us/libr...2d(VS.80).aspx

So in header file writing: const double PI = 3.14;
Every time using it, include the header file.

But how about constants in namespaces and classes?

Thanks for your help!

Shuisheng

1. The easiest constants in classes are made by using enums:
#include <vector>

class SomeClass
{
enum { SIZE= 7 };

int array[SIZE];

std::vector<int intVector;
public:
SomeClass(): intVector(SIZE) {}
};

2. Regarding global constants and the header file you mentioned, in
simple words:

You can #include the header file with the global constant only in one
"implementation " file (e.g. .cpp) and to the rest implementation files
(e.g. .cpp), you can add the declaration:
extern const double PI;
==In general avoid objects in the global namespace.

3. Regarding constants in namespaces, you have to include the definition
in the implementation file (e.g. by placing it in the header file).
file1.cpp:
E.g. pi.h:

namespace SomeNamespace
{
const double PI = 3.14;
}


What should be preferred instead of constants in the global namespace:

Constants (consts/enums) in anonymous namespaces (= local file scope
only), and constants (consts/enums) in named namespaces.
Regarding classes, you can either use static constants or (usually
better) enums.

Oct 14 '08 #4
Ioannis Vranos wrote:
Corrected:
[..]

Regarding classes, you can either use static constants or (usually
better) enums.
Well, there aren't double or string enums, so... The difference between
the class [non-integral] constants and the namespace ones is that the
class constants have to be declared in the class and *defined* in some
translation unit, while the namespace constants can be defined in the
header (which means they will be duplicated in every translation unit
that includes the header), which is OK because they have internal
linkage (unless you specify otherwise).

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Oct 14 '08 #5
On Oct 14, 1:20*pm, Victor Bazarov <v.Abaza...@com Acast.netwrote:
Ioannis Vranos wrote:
Corrected:
[..]
Regarding classes, you can either use static constants or (usually
better) enums.

Well, there aren't double or string enums, so... *The difference between
the class [non-integral] constants and the namespace ones is that the
class constants have to be declared in the class and *defined* in some
translation unit, while the namespace constants can be defined in the
header (which means they will be duplicated in every translation unit
that includes the header), which is OK because they have internal
linkage (unless you specify otherwise).

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
So I think the following is the right way, please confirm it. I use PI
as an example.

For global constants:

// in constants.h
const double PI = 3.14;

// in h or cpp files to use PI
#include "constants. h"
double a = PI;
For constants in namespace:

// in constants.h
namespace constants
{
const double PI = 3.14;
};

// in h or cpp files to use PI
#include "constants. h"
double d = constants::PI;
For constants in classes:

// in class.h
class A
{
public:
static const double PI;
};

// in class.cpp
const double A::PI = 3.14;

// in h and cpp files to use it.
#include "class.h"
double a = A::PI;

And I think Ioannis Vranos's way to define global constants will bring
about problems as shown in http://msdn.microsoft.com/en-us/libr...2d(VS.80).aspx

Thanks and best regards,
Oct 14 '08 #6
shuisheng wrote:
[..]
So I think the following is the right way, please confirm it. I use PI
as an example.

For global constants:

// in constants.h
const double PI = 3.14;

// in h or cpp files to use PI
#include "constants. h"
double a = PI;
For constants in namespace:

// in constants.h
namespace constants
{
const double PI = 3.14;
};

// in h or cpp files to use PI
#include "constants. h"
double d = constants::PI;
For constants in classes:

// in class.h
class A
{
public:
static const double PI;
};

// in class.cpp
const double A::PI = 3.14;

// in h and cpp files to use it.
#include "class.h"
double a = A::PI;

And I think Ioannis Vranos's way to define global constants will bring
about problems as shown in http://msdn.microsoft.com/en-us/libr...2d(VS.80).aspx
The code you showed here is perfectly fine, and you can declare/define
any constants that way, not just of fundamental types, AFAIC.

The contents of the web page you cited do bother me. I am not sure what
"static linkage" is; there is no such term in C++ Standard. Why would
the page say that "If you try to use a global constant in C++ in
multiple files you get an unresolved external error"? What kind of
nonsense is that? If you *do* declare some object "extern", then you
must define it somewhere. If you don't defined it, you violate the ODR.

The point in using constants like you've shown is that there *is* a
*defined* object in every module, it has internal linkage (since it's
declared 'const' and does not have external linkage), and that's it.
Whether those objects are "optimized out" does not matter. From the
language point of view they exist, have value, are constant, and that's
about all we need to know.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Oct 14 '08 #7
On Oct 14, 4:58*pm, Victor Bazarov <v.Abaza...@com Acast.netwrote:
shuisheng wrote:
[..]
So I think the following is the right way, please confirm it. I use PI
as an example.
For global constants:
* // in constants.h
* const double PI = 3.14;
* // in h or cpp files to use PI
* #include "constants. h"
* double a = PI;
For constants in namespace:
* // in constants.h
* namespace constants
* {
* * const double PI = 3.14;
* };
* // in h or cpp files to use PI
* #include "constants. h"
* double d = constants::PI;
For constants in classes:
* // in class.h
* class A
* {
* public:
* * static const double PI;
* };
* // in class.cpp
* const double A::PI = 3.14;
* // in h and cpp files to use it.
* #include "class.h"
* double a = A::PI;
And I think Ioannis Vranos's way to define global constants will bring
about problems as shown inhttp://msdn.microsoft. com/en-us/library/0d45ty2d(VS.80) .aspx

The code you showed here is perfectly fine, and you can declare/define
any constants that way, not just of fundamental types, AFAIC.

The contents of the web page you cited do bother me. *I am not sure what
"static linkage" is; there is no such term in C++ Standard. *Why would
the page say that "If you try to use a global constant in C++ in
multiple files you get an unresolved external error"? *What kind of
nonsense is that? *If you *do* declare some object "extern", then you
must define it somewhere. *If you don't defined it, you violate the ODR..

The point in using constants like you've shown is that there *is* a
*defined* object in every module, it has internal linkage (since it's
declared 'const' and does not have external linkage), and that's it.
Whether those objects are "optimized out" does not matter. *From the
language point of view they exist, have value, are constant, and that's
about all we need to know.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
I tested using "extern" as following in visual studio 2005.

//! in constants.h
extern const double PI;

//! in constants.cpp
const double PI = 3.14;

When using for multiple files, especially when PI is defined in a
library, it gives a link error. I think C++ treats global constants
different from global non-constant variables. My understanding is
that: there is no external objects somewhere for global constants,
even in "constants. cpp" having the code "const double PI = 3.14;".
Oct 14 '08 #8
shuisheng wrote:
>
So I think the following is the right way, please confirm it. I use PI
as an example.

For global constants:

// in constants.h
const double PI = 3.14;

// in h or cpp files to use PI
#include "constants. h"
double a = PI;

This is OK, but try not polluting the global namespace.
>
For constants in namespace:

// in constants.h
namespace constants
{
const double PI = 3.14;
};

// in h or cpp files to use PI
#include "constants. h"
double d = constants::PI;

There are also the anonymous namespaces which have local file scope:
namespace
{
const double PI= 3.14;
};
For constants in classes:

// in class.h
class A
{
public:
static const double PI;
};

// in class.cpp
const double A::PI = 3.14;

// in h and cpp files to use it.
#include "class.h"
double a = A::PI;

or enums for integer constants.
And I think Ioannis Vranos's way to define global constants will bring
about problems as shown in http://msdn.microsoft.com/en-us/libr...2d(VS.80).aspx

Yes you are right. This is one of the differences between C++ and C.

Victor check TC++PL3 on page 200.
const int x= 7; in global scope is equivalent to

static const int x= 7;
For this to work as C, definition must be accompanied with the word
extern, that is:
extern const double PI= 3.14;
But as I said, we must avoid global variables as much as possible and
must avoid polluting the global namespace as much as possible.
Oct 14 '08 #9
Recorrected:
shuisheng wrote:
Dear All,

I am always confused in using constants in multiple files.

For global constants, I got some clues from
http://msdn.microsoft.com/en-us/libr...2d(VS.80).aspx

So in header file writing: const double PI = 3.14;
Every time using it, include the header file.

But how about constants in namespaces and classes?

Thanks for your help!

Shuisheng

Corrected:

shuisheng wrote:
Dear All,

I am always confused in using constants in multiple files.

For global constants, I got some clues from
http://msdn.microsoft.com/en-us/libr...2d(VS.80).aspx

So in header file writing: const double PI = 3.14;
Every time using it, include the header file.

But how about constants in namespaces and classes?

Thanks for your help!

Shuisheng

1. The easiest constants in classes are made by using enums:
#include <vector>

class SomeClass
{
enum { SIZE= 7 };

int array[SIZE];

std::vector<int intVector;
public:
SomeClass(): intVector(SIZE) {}
};

2. Regarding global constants and the header file you mentioned, in
simple words:

i) You can #include the header file (e.g .h) in all implementation files
(e.g. .cpp), keeping in mind that as a result, each instance of the
constant (defined as const double PI= 3.14;) is a different file-scope
(more accurately, compilation unit - scope) object.
ii) You can #include the header file with the global constant in the form:
extern const double PI= 3.14;
in one "implementation " file (e.g. .cpp) and to the rest implementation
files (e.g. .cpp), you can add the declaration:
extern const double PI;


==In general avoid objects in the global namespace.

3. Regarding constants in namespaces, you have to include the definition
in the implementation file (e.g. by placing it in the header file).
E.g. pi.h:

namespace SomeNamespace
{
const double PI = 3.14;
}


What should be preferred instead of constants in the global namespace:

Constants (consts/enums) in anonymous namespaces (= local file scope
only), and constants (consts/enums) in named namespaces.
Regarding classes, you can either use static constants or (usually
better) enums.
Oct 14 '08 #10

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

Similar topics

0
1218
by: Sugapablo | last post by:
I'm trying to use the Const statement to define a group of constants. I would like different groups of constants, one for each language (such as english, spanish, etc.) Depending on a variable (cookie, querystring, etc.) I would like the constants to be defined differently. One thing I tried was: --------------------------------------------------------
4
2569
by: gabriel | last post by:
Greetings, I am working on a project and cannot choose the best way to achieve this : I got a method which returns an error code like this : DISK_FULL or PERMISSION_DENIED. Those are constants defined in a class named "Constants" : public static byte DISK_FULL = 1;
13
3071
by: poison.summer | last post by:
Hello If I have an enum definition for instance typedef enum { F0 = 0, F1 = 1, F2 = 2, F3 =3
2
1841
by: yawnmoth | last post by:
The PHP license states the following: 4. Products derived from this software may not be called "PHP", nor may "PHP" appear in their name, without prior written permission from group@php.net. You may indicate that your software works in conjunction with PHP by saying "Foo for PHP" instead of calling it "PHP Foo" or "phpfoo" As the author of something released under the PHP license, can I, as I see fit, just grant permission to an...
4
2024
by: D. Yates | last post by:
Hi all, Is there a place in the .NET framework where simple time constants are defined? For example: How many days are there in a week? Hours in a day? Minutes in an hour? Seconds in a minute? None of these are going to change, so they are obviously constants. Now I
10
1590
by: Steven W. Orr | last post by:
I saw this and tried to use it: ------------------><8------------------- const.py------------- class _const: class ConstError(TypeError): pass def __setattr__(self,name,value): if self.__dict__.has_key(name): raise self.ConstError, "Can't rebind const(%s)"%name self.__dict__=value
3
1266
by: Steven W. Orr | last post by:
This is all an intro learning experience for me, so please feel free to explain why what I'm trying to do is not a good idea. In the Cookbook, they have a recipe for how to create global constants. ----------------- class _const: class ConstError(TypeError): pass def __setattr__(self,name,value): if self.__dict__.has_key(name):
6
1642
by: lazy | last post by:
hi, I have some constants defined in a php script say config.php. I want to use the variables there defined in other scripts. couple of questions regd that: 1. Is there an alternative to including config.php and declaring the variables that will be used as global. This seems very inefficient. 2.Moreover these variables are constants, is there a way to make the variables unmodifiable in config.php so that scripts that use them ,
3
1690
by: Microsoft | last post by:
Hi I have a c# program that continually runs 24/7 and performs a variety of tasks based on a timer. There is one routine that hangs every Saturday morning without fail. If I restart the program throughout the week is still hangs. I can restart it immediatly after the hang and it runs fine until next Saturday. There is nothing different about Saturday that I can think of.
0
9957
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9799
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11173
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10771
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...
1
7988
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7143
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
5810
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
6011
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3245
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.