Search code examples
cassemblycompilationlinker

In C When `x=9;` compiled does the lvalue on the left hand side of the `=` replaced with address of `x`? and if so, why is `&x=9` illegal?


I am a C tutor and dev that is trying to deepen my understanding about what's going on during compilation. I have come across C tutorial which says that

After compilation there are no more variable names, just addresses

I assume the the left operand of the = operator must be an ADDRESS!
Following that logic, it's safe to assume that the assembly command for x=9 will be something like:
put the literal 9 into the address of x

So isn't it safe to say the the lvalue x is replaced with its own address?
And if so - why isn't is possible to just give the address directly like so:
&x=9
Which seems to me will result in the same assembly commands..
After all, this lvalue on the left hand side will be evaluated to its address, and this address will be sent as an operand to the = operator


Solution

  • Variable is just a chunk of memory. Assume that integer is 4 bytes long.

    int x;
    
    /* ... */
    
    x = 9;
    

    Simplifying: x has to be stored somewhere in the memory. Memory cells are identified by their addresses. The compiler and linker convert the human-readable symbol x to the addresses of some memory cells in memory. Machine code instructions write some values (in our case 4 bytes) representing the number 9. In most modern implementations it will be 9,0,0,0.

    In real life, it can more complicated as the compiler can keep it in registers or optimize it out completely.

    And if so - why isn't is possible to just give the address directly like so: &x=9

    &x is a reference to the object x. You can't assign it as it is a fixed location in memory (you can't change it). But you can of course dereference (access) this location

    *&x = 9;
    

    References (addresses) can be assigned to pointers.

    int x = 0;
    int *pointer = &x;