Re: extern const
Ivan Novick wrote:
My question is, should there be a compiler warning or error when x is
declared in test.cpp non-const to refer to a const variable in
info.cpp?
//////////////////////////////////////////////////////////
// info.cpp
extern const int x = 4;
//////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////
// test.cpp
#include <iostream>
extern int x;
int main()
{
std::cout << "x: " << x << std::endl;
++x;
std::cout << "x: " << x << std::endl;
return 0;
}
I don't know what the linker's obligations are in this situation, and
have little interest in finding out. In other words, I would not have
the linker manage the const variable "x" in the first place. After all,
if the linker were not in the picture, then questions like the one
above would cease to be interesting.
A more simple, more reliable way and more efficient way to manage x
would be to move x's const declaration into a header file:
// test.h
const int x = 4;
The only other step is to have each source file that uses "x" to
include this header file (test.h in this example).
The effect of this change is to enable the C++ compiler to manage "x"
instead of the linker. Compiler-management of const values has several
advantages over "linker-management" of the same. With x defined in a
header file, the program is assured of a consistent value for x - a
value moreover that is known at compile time. So instead obtaining x's
constant value at runtime by reading a location in memory (as the
original program had to do), the compiler can simply replace
occurrences of "x" in the source with the hardcoded value: 4. In fact,
with x's value known to the compiler, there is no longer any need to
allocate storage for x (unless its address is taken for some strange
reason).
So to recap: with this change, the program has become not only faster
(by eliminating the runtime memory access of x's value) but has become
smaller as well (by eliminating x's storage). Granted, both the number
of cycles eliminated and bytes saved are tiny in the case of a single
constant variable. But when multiplied across all of a program's const
values, then these numbers may start to add up.
Lastly, I should point out (lest anyone else feel compelled to) that
this example is not entirely realistic. In a "real" program, "x" would
have a more informative name. Furthermore, a program (especially a
large one) may also elect to declare a namespace to hold x and any
other related constants - in order to avoid potential name collisions
or to help dilineate (and document) the various parts comprising the
program.
Greg
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]