S
subramanian100in
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 ?
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 ? 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.
Please correct me wherever I have gone wrong.
Kindly explain.
Thanks
V.Subramanian
const variables at global scope are local to a file by default.
What is the advantage of this rule ?
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 ? 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.
Please correct me wherever I have gone wrong.
Kindly explain.
Thanks
V.Subramanian