3

C++ Primer said if the const can initialize while compile, it will swap the identifier to the value used when initialize, so why I can get the address of a const initialize while compile?

  • It _can_, but only if the observable behaviour wont change, it's called the [As-If rule](https://stackoverflow.com/questions/15718262/what-exactly-is-the-as-if-rule). – Lukas-T Jun 25 '20 at 10:28
  • look at the assembly code for this [example](https://godbolt.org/z/jTew_f) you can see that when it prints a it change it to 5 but in b he called the variable – yaodav Jun 25 '20 at 10:29
  • Yeah, the result is expected, if I didn't use & operator, it will not allocate memory –  Jun 25 '20 at 12:01

1 Answers1

8

The key word in that statement is can. If the compiler can then it may replace your constant with a literal at compile time. If you take the address of the constant then the compiler must allocate memory for it so that there is something to point to. Even if you do this it may still use the literal instead of the memory location when you use the constant in other places.

Alan Birtles
  • 32,622
  • 4
  • 31
  • 60
  • 1
    `If you take the address of the constant then the compiler must allocate memory`... if that is observable to the behaviour of the program that is. If you don't let the pointer get to the outside of the function, compiler might still be able to not allocate memory. In theory at least. – eerorika Jun 25 '20 at 10:31
  • So if I used & operator on it, the compiler will allocate memory for it? –  Jun 25 '20 at 10:48
  • 1
    @AlanJian Maybe. Sometimes the obtained pointer can be optimized away too. Compilers are quite good at removing things that are not required. – Lukas-T Jun 25 '20 at 11:10