Since first and last address are same or the address in &pi and a are same, is the address in a is from constant data segment or free store area?
int main()
{
const int pi = 10;
cout <<"This is constant memory area's address " << &pi << endl;
int *a = new int;
cout << "This is free store memory area's address " << a << endl;
a = (int*) π
cout << *a << endl;
cout << "This is free store memory area's address " <<a << endl;
return 0;
}
Your concepts are not correct. There are side effects or limitations in your program.
The statement:
const int pi = 10;
Declares a constant. The compiler can put the constant wherever it wants.
Here are some possible locations:
However, the moment you take the address of the constant, the compiler cannot store the value in these places:
move reg_a, #10
Also, pointers can live in registers too. However, taking the address of a pointer prevents the pointer from living in a register, since using the &
operator requires that the variable live in an addressable memory location and registers are not addressable via pointer.
BTW, you have a memory leak:
a = new int;
a = π
The last statement looses or leaks the location of the dynamically allocated integer.
Note: There are some processors in which registers live in an addressable location in memory; but these are exceptions.
Edit 1: Symbol Tables
When you declare a variable as const
and assign it a literal, the compiler can store the variable in a table of <symbol, value> and not take up any variable space in the program.
When the compiler encounters the symbol, eg pi
, it can look up the symbol, pi
, in its table and substitute the value (10). So the expression:
int b = pi;
will become, after substitution:
int b = 10;
Thus your pi
variable doesn't have any allocated space, in your program . In the above example, the value of the variable is placed into your program.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.