Search code examples
cpointersunary-operator

What does C's unary '&' do? Why doesn't it work on constants?


I am trying to make a new programming language, and I am trying to add the & (pointer-to) operator from C. What exactly does it do? That is, how does it 'create' a pointer? Why can't it create a pointer to a constant1? My current implementation of the operator is as follows, but it also works on constants, so I assume it is not how the C operator works:

operator & (any one argument):
    temp = allocate (typeof argument)
    store argument in temp
    return temp

1: example program:

int main(){
    int* x;
    x = &1;
}

gcc output:

ptr.c: In function ‘main’:
ptr.c:3:6: error: lvalue required as unary ‘&’ operand
  x = &1;

Solution

  • C's unary & gives you the address of the thing it's applied to.

    So for example, &x gives the address of x.

    It doesn't create a new variable, copy x into that variable and then return the address of the new variable. It returns the address of x, plain and simple.