Bartłomiej Zieliński
Bartłomiej Zieliński

Reputation: 997

How does C handle operation precedence in case of two increments and indirection operator?

Yesterday, I stumbled upon a sample code from university lecturer (I give private lessons to one of his students). I'm trying to understand, why and how does this code work, but I'm still not sure, even after a couple of hours of research. Here's what I have:

int tab[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int* t = tab;
int i;
for (i = 0; i < 10; i++)
{
    (*t++)++;
    printf("%d ", tab[i]);
};

The result is:

1 2 3 4 5 6 7 8 9 10

So, this code is quite easy to understand, except for this part:

(*t++)++

I know that incrementation operator takes precedence over indirection operator, so this operation will be most probably handled as:

(*(t++))++

Considering that t is a pointer, I would say that this would happen:

  1. t address will be incremented, so it will point to a second element in tab array (index 1).
  2. Now, indirection operator should be processed, so the value of second element in tab array will be incremented, because we end up with (*t)++.

Now, my question is, why all tab elements are incremented? Shouldn't it skip the first tab element (index 0), considering that the pointer incrementation happens right at the start of the loop?

Upvotes: 2

Views: 102

Answers (2)

Jean-Baptiste Yun&#232;s
Jean-Baptiste Yun&#232;s

Reputation: 36431

Operator precedence says that *t++ must be decomposed as *(t++). Thus the expression is like (*t)++; t++;

Confusion may come when you don't understand what t++ means, the value of this expression is the value of t before the increment, and t can be observed as incremented after the (whole) expression being evaluated.

Upvotes: 3

Vlad from Moscow
Vlad from Moscow

Reputation: 311088

You can imagine the evaluation of this expression

(*t++)++;

as a sequence of the following statements

int *tmp = t;
( *t )++;
++tmp;
t = tmp;

From the C Standard (6.5.2.4 Postfix increment and decrement operators)

2 The result of the postfix ++ operator is the value of the operand. As a side effect, the value of the operand object is incremented (that is, the value 1 of the appropriate type is added to it).

Upvotes: 0

Related Questions