Search code examples
cpointersoperatorsoperator-precedence

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?


Solution

  • 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.