Using & (addressof) with constant variables in C

Text books argue that the operator (addressof) does not apply to cannot be applied to expressions,
constants or register variables.
Are there only literals such as "A", "7", etc.? Or variables declared with the const keyword?

I think this only means literals, as the following code compiles: -

int main() { const int i=10; const int *ip; ip = &i; 

}

+2
source share
3 answers

No - it can be applied to a variable that qualifies as const . Note, however, that doing this (in the general case) means that the compiler must actually assign this variable to an address - if you use it only in ways that don't need an address, the const variable will often not be needed (i.e. the code generated with using the const variable will often look like you will use the literal directly, but the source code will use a meaningful name instead).

+3
source

The unary & operator in C can be applied to any lvalue. The object constructed by const is an lvalue, which means that unary & can be applied to it.

The term "constant" in C really only means literal constants, for example, 2 . An object constructed by const is not a "constant" in C. terminology

+3
source

&operator can be applied to anything that has a memory address. You cannot apply & to register variables, because they are stored in CPU registers.
Also, in C constants are not compile-time constants (i.e., Always allocated memory), so you can safely accept the address of a constant variable. But in C++ , if you take the address of the const variable, it will not be a compile-time constant and storage will be allocated.
<b> Change
In terms of constants, I mean that variables declared with the const keywords, literals such as A, 7, are essentially compilation. Constants.compiler can directly store them in its character table.

0
source

Source: https://habr.com/ru/post/1271383/


All Articles