For example, after we define a variable:
int a=2;
we can use “a” as 2 afterwards.
At the time when I first learned c/c++, I took it for granted.
But after I have learned the concept of “pointer” and the address of variables, I am confused.
If int* p=&i;, where “i” is an int. I know that p have the address of i, so we can use *p to get the value of i. But if we go further, how is “p” accessed? It seemed that p must be referenced by name,right?
By now, to access a variable via its address seems more natural to me and easier to understand.
But now , I’m a confused about the mechanism when using the most simple way to access a variable.
As in the case of int a=2; , where is the name “a” stored?
Why if we use “a”, it is equivalent to the behavior of accessing the memory where the “a” or the “2” is stored?
Here
ais just a symbolic name. If it’s a local variable, it ain’t stored anywhere. Compiler simply uses it during the compilation phase, referencing the actual value (which can be on the stack or in register), then discards.If you looked at the assembly generated by compiler, you’d notice that
aisn’t appearing there (or maybe in comments). Compiler will fit your variable somewhere, and just use that location afterwards (like theeaxregister on x86).If you looked at an LLVM assembly (which is quite interesting), you’d notice that the compiler just treats your variables as
@1,@2,@3…On the other hand, if
awould be a global variable (and a non-staticone), the name would actually be used in the symbol table to reference the variable. But it’d be the other way around — variable would be placed somewhere without the name, and the symbol table would map that name to the location so that other programs could find it.As a side note: if the program is compiled with debug data, the name
ais stored there so that the debugger could display it to help you understanding what’s happening.