TITLE: const and internal linkage (Newsgroups: comp.std.c++, 8 May 97) UNKNOWN: > : >class A > : >{ > : > public: > : > static const int x = 5; > : > ... > : >}; > : > > HENDERSON: Fergus Henderson > : > : ... you still need a definition of `X::x', i.e. > : const int A::x; > : somewhere. ZABLUDA: Oleg Zabluda > I have a question. A compiler is free (I think) not to allocate > any storage for constants, unless their address is needed, right? > For example, in > > const int a = 5; > const int b = 3; > int main(){ > sleep(a); > const int * pi = &b; > } > > a compiler is free not to allocate any storage for a, but must > allocate a storage for b. > > Now, I know that in practice you probably won't notice an error, > if you skip 'const int A::x;' in the example above, or you'll > only find out about the error on the link stage. > > Now, the question is: did anyone try to formalize these requirements, > so that 'const int A::x;' becomes optional under well-defined > conditions. After all, this is a real performance issue, and the one > that can make the dreadful #define's preferable to a const variables > under some circumstances. CLAMAGE: Steve Clamage An object declared const at namespace scope has internal linkage unless declared extern (draft 7.1.1 Storage class specifiers). Your example shouldn't result in a link error even if no storage is allocated for object 'a', since 'a' cannot be referenced by name from any other translation unit. The 'x' member of A does not have namespace scope. It is a static data member of a class, and thus has extern linkage. The compiler is not allowed to omit storage for extern objects if such an omission would result in any sort of program failure or change in semantics. Because 'x' is declared const, the compiler can use its defined value any place 'x' is referenced. So even if storage is allocated for x, you do not lose the other benefits of const objects.