c

does *x = *x + 1 add 1 to the value of x or to the address of x?


I was studying about bubble sort and I came by this expression. It seems like the equation adds 1 to the address of x but the video said it adds one to the value of x. Can someone please explain and confirm which one is the right explanation?

I didn't try out anything.


Solution

  • See C operator precedence table.

    So, expression

    *x = *x + 1;
    

    is same as

    (*x) = ((*x) + 1);
    

    and *x means the value, more accurately lvalue, ie. value which can be on the left side of assignment, at the address where pointer x points to.

    So, it takes the value from *x, adds 1 to the value, then assigns it back to *x.

    It's same as *x += 1;