What does it mean if you assign to a variable with two plus signs?

Viewed 103

What does this mean:

*variablename++ = ',';

I have seen stuff like i++ which does: i = i + 1 this I guess.

But what does it mean if you assign a thing to it like the above (first one)?

2 Answers

This is a common way to assign elements of an array (by using a pointer) inside a loop.

Without knowing the exact type, it's equivalent to something like:

{
    type *old_pointer = variablename;  // Substitute type for the actual type

    variablename = variablename + 1;

    *old_pointer = ',';
}

The important part here is that the variable must be a pointer. You can't do it using non-pointer types like int. That's because the suffix increment operator returns an rvalue (see e.g. this value category reference for details), and rvalues can't be assigned to.

But if the rvalue is a pointer, then it can be dereferenced to become an lvalue, which can then be assigned to.

Post increment operator ++ has heigher precedence than indirection operator *. In addition, the post increment "returns" the previous value of the variable (in our case, the previous value of the pointer before the increment). So the code above is as the same as:

*variablename = ',';    
variablename = variablename + 1;
Related