What is the difference between * var ++ and * var + = 1?

14

I am writing a function with the signature: int increment(int *val) . My intention is to get an integer pointer, increment its value in 1 and return that value.

The body of my function was as follows:

int increment(int *val)
{
    *val += 1; // Dessa maneira o valor de val é incrementado em 1.
    return *val;
}

In the commented line, when I used the unary operator ++ , as in *val++; I received the changed memory address.

Why does using the unary operator modify the memory address? Theoretically it was not meant to be equal to *val += 1 ? Thanks for any examples.

    
asked by anonymous 22.11.2015 / 18:35

2 answers

16

This occurs because of the precedence of operators.

The += has low precedence, so the pointing operator occurs first, then it does increment in the value pointed.

The ++ has higher precedence, so first it increments the value of the val variable that is a pointer, then it applies the pointing operator and takes the value pointed to by this calculated address. just put parentheses to solve the problem of precedence:

(*val)++;

See working on ideone .

Precedence table .

    
22.11.2015 / 18:48
6

This happens because of the order of precedence of the operations. The increment operator (++, -) takes precedence over the * operator.

So, in order for it to work the way you want, you must first have access to the content pointed to by the val variable. For this you do * val , soon after you do the ++ increment.

In order for you to accomplish this in order, you need to use parentheses.

See:

(*val)++;
    
22.11.2015 / 18:54