On Nov 30, 1:36 pm, "subramanian10...@yahoo.com, India"
<subramanian10...@yahoo.comwrote:
I read in C++ Primer 4th Edition by Stanley Lippman, in page 57, that
const variables at global scope are local to a file by default.
What is the advantage of this rule ?
To confuse people, and frustrate programmers. It's obviously a
mistake, but for whatever reasons, it's there, and it can't be
changed at this late date.
Suppose I have the following const variable defined in a.h
const int const_int = fn();
Suppose a.h is #included in a.cpp which also contains the following
function.
int fn()
{
static int counter;
return ++counter;
}
Assume a.cpp uses the variable 'const_int'. Suppose a.h is #included
in another file b.cpp which uses 'const_int'
We will get different values for the const int variable 'const_int'
when it is used in these two files. Am I correct ?
You have two different variables, with two different values,
yes. If you only want one, then you have to declare:
extern int const const_int ;
in the header, and:
extern int const const_int = fn() ;
in one (and only one) source file.
Which, by the way, might explain why the rule is there. Here,
it's not an issue, because the initialization expression is not
const itself, but if you want to use the variable as a compile
time constant (integral constant expression), then the compiler
has to see the initializer. Which means that the initializer
must be present in the header, which means that the header must
contain a definition, not a declaration, which means that if it
doesn't have internal linkage, you have a violation of the one
definition rule.
There are other ways around this; the way static const is
handled in a class, for example. But they also cause some
confusion, and I don't think that the compiler technology in the
early days of C++ would have easily supported them.
This situation arises because the compiler allows a non-const
expression to be used as the initializer for the const
variable and yet it allows the const variable to be available
local to the files.
Why doesn't the compiler DISALLOW this ? ie If the compiler
disallows a const variable to be defined in multiple .cpp
files, this will not arise.
I think you mean "if the compiler allowed a const variable to be
defined in multiple source files". It does, in the case of
static members, but that's very much an exception. And I'm not
sure that the technology to support this was available in the
early days.
--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34