Where and how are constants stored?

c++, constants, memory

Solution

You cannot take the address of a literal (e.g. `&(5)`) because the literal is not "stored" anywhere - it is actually written in the assembly instruction. Depending on the platform, you'll get different instructions, but a MIPS64 addition example would look like this:

DADDUI R1, R1, #5

Trying to take the address of the immediate is meaningless as it doesn't reside in (data) memory, but is actually part of the instruction.

If you declare a `const int i = 5`, and do not need the address of it, the compiler can (and likely will) convert it to a literal and place `5` in the appropriate assembly instructions. Once you attempt to take the address of `i`, the compiler will see that it can no longer do that, and will place it in memory. This is not the case if you just attempt to take the address of a literal because you haven't indicated to the compiler that it needed to allocate space for a variable (when you declare a `const int i`, it allocates the space in the first pass, and will later determine it no longer needs it - it does not function in the reverse).

String constants are stored in the static portion of the data memory - which is why you can take the address of them.

Problem

I read this question from here and I also read related question from c-faq but I don't understand the exact reason behind this :- ``` #include <iostream> using namespace std; int main() { //const int *p1 = (int*) &(5); //error C2101: '&' on constant //cout << *p1; const int five = 5; const int *p2 = &(five); cout << *p2 << endl; char *chPtr = (char*) &("abcde"); for (int i=0; i<4; i++) cout << *(chPtr+i); cout << endl; return 0; } ``` I was wondering how constants, either integer or string literal, get stored. My understanding of string literals is that they are created in global static memory upon start of program and persist until program exit. In the case of `"abcde"` even though I did not give it a variable name I can take it's address (`chPtr`) and I assume I could probably dereference `chPtr` any time before program termination and the character values would still be there, even if I dereferenced it outside the scope where it was declared. Is the `const int` variable `"five"` also placed in global static and that address `p2` can also be referenced any time? Why can I take the address of `"five"` but I cannot ask for: `&(5)` ? Are the constants `"5"` and `"five"` stored differently? and where `"5"` is get stored in memory ?

Original source