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

Asked

Viewed 1,239 times

15

I’m writing a feature with the signature: int increment(int *val). My intention is to receive an entire pointer, increase 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.

Because when using the unary operator does it modify the memory address? Theoretically it was not meant to amount to *val += 1? Thank you if there are examples explaining.

2 answers

16


This occurs because of the precedence of operators.

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

The ++ has higher precedence, so first it increments the value of the variable val which is a pointer, then it applies the pointing operator and picks up the value pointed by this calculated address. simply place parentheses to solve the problem of precedence:

(*val)++;

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Precedence table.

6

This is due to the order of precedence of the operations. The increment operator (++,-) takes precedence over the operator *.

Therefore, in order to work the way you want, you first need to have access to content pointed by the variable val. That’s what you do *val, soon after you make the increment ++.

In order for you to achieve this order, it is necessary to use parentheses.

Behold:

(*val)++;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.