The keyword const
indicates a variable that is read-only (i.e., cannot be changed at run-time). It does not indicate a compile-time constant. Therefore, all of the usual attributes of variables apply; specifically, it is allocated addressable storage space.
Unlike with #define
, your constant is not necessarily inlined by the compiler. Rather, the compiler will create a symbol corresponding to your const
declaration in the object file so that it can be accessed from other code files—remember that const
objects have external linkage by default in C (although some compilers will still inline the constant value within the file where it is defined).
The reason the code snippet that you posted "works" is because the unary operator &
can be applied to any lvalue, which includes a const
object. Though the behavior here is undefined, I suspect that your compiler is detecting this usage and ensuring that your const
declaration is given address space, and therefore not inlining it, even within the file it is declared.
EDIT: Also see: http://publications.gbdirect.co.uk/c_book/chapter8/const_and_volatile.html
Let's look at what is meant when const
is used. It's really quite simple:
const means that something is not
modifiable, so a data object that is
declared with const as a part of its
type specification must not be
assigned to in any way during the run
of a program. It is very likely that
the definition of the object will
contain an initializer (otherwise,
since you can't assign to it, how
would it ever get a value?), but this
is not always the case. For example,
if you were accessing a hardware port
at a fixed memory address and promised
only to read from it, then it would be
declared to be const but not
initialized.
Taking the address of a
data object of a type which isn't
const and putting it into a pointer to
the const-qualified version of the
same type is both safe and explicitly
permitted; you will be able to use the
pointer to inspect the object, but not
modify it. Putting the address of a
const type into a pointer to the
unqualified type is much more
dangerous and consequently prohibited
(although you can get around this by
using a cast). For example...
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…