Using & (addressof) with const variables in C
Text books say that & (addressof) operator doesn't apply to cannot be applied to expressions,
constants, or register variables. Does constants mean only literals like 'A', '7' etc or variables declared with const keyword as well? I think this mean on开发者_JAVA百科ly literals since following code compiles:-int main()
{
const int i=10;
const int *ip;
ip = &i;
}
Unary operator &
in C can be applied to any lvalue. A const-qualified object is an lvalue, which means that unary &
can be applied to it.
The term "constant" in C indeed means only literal constants, like 2
, for example. A const-qualified object is not a "constant" in C terminology.
No -- it can be applied to a variable that's qualified as const
. Note, however, that doing so (generally) means that the compiler has to actually assign that variable an address -- if you only use it in ways that don't need an address, a const
variable often won't need to be assigned any storage at all (i.e., the code generated using a const
variable will often be almost like you'd use a literal directly, but your source code gets to use a meaningful name instead).
&operator
can be applied to anything that has a memory address.You cannot apply &
on register variables as they are stored on CPU registers.
Also in C
, constants are not compile time constants(i.e always allocated storage), so you can safely take address of a constant variable.But in C++
, if you take address of a const
variable it will not be a compile time constant and will be allocated storage.
Edit
By constants i mean, variables declared with const
keywords, literals like A,7, are essentially compile time constants.compiler can directly store them in its symbol table.
精彩评论