Does extern "const" allocate storage?
Karl Heuer
karl at haddock.ISC.COM
Fri Mar 18 04:02:24 AEST 1988
In article <7712 at apple.Apple.Com> lenoil at apple.UUCP (Robert Lenoil) writes:
>I'm having some trouble understanding the const type qualifier. If I declare
> const int foo = 3;
>then I hope that the compiler would actually use the constant 3 whenever foo
>is used, instead of allocating storage and generating a reference to foo.
The compiler is certainly free to do so. (But if this declaration has file
scope, you'd better declare it "static" as a hint to the compiler that no
other module uses it.)
>One exception, however, would be if I declare
> const int *bar = &foo; ["&" added --kwzh]
>which would have to allocate storage for foo so that a pointer to foo could be
>placed in bar. My question involves what happens when foo is defined in
>another module? Does
> extern const int foo;
>expect to be linking to an external constant, or is it linking to an external
>integer, and semantically prohibiting assignment to that integer?
What do you mean by "linking to an external constant"?
>What about
> extern const char foo[];
>I suppose that's illegal, because sizeof(foo), which should be a constant,
>won't work.
No, it's quite legal, just as for a non-const array. You can't apply sizeof
to an incomplete type.
>The ANSI C draft of 1/11/88 mentions the const type qualifier in section
>3.5.3 but doesn't actually define its meaning.
It doesn't describe the implementation details, if that's what you mean. The
dpANS defines the valid operations and their semantics; whether storage is
actually allocated is a "quality" issue, beyond the scope of the standard.
You seem to be asking whether const is at least as efficient as #define.
Let's assume we're talking about a header file that is shared among multiple
modules. If you use "static int const foo=3;" and never take its address, a
good compiler ought to be able to inline it wherever it's used. (If you do
take its address, you couldn't have used a #define anyway, so the comparison
is invalid.) If you use "extern int const foo;" and somewhere else you have
the definition "int const foo=3;", then the compiler will probably allocate
storage, unless it has some way to intuit the value. (It could still be more
efficient than a non-const reference, though.)
(Btw, I intentionally wrote "int const" rather than "const int". "const" is a
qualifier, not a storage class; it modifies "foo", not "int".)
Karl W. Z. Heuer (ima!haddock!karl or karl at haddock.isc.com), The Walking Lint
More information about the Comp.lang.c
mailing list