Search code examples
coperator-precedence

What will be result of code execution? C Operator Precedence


I have a problem with predicting result of code linked below. Why program is printing 2 0 6 0 10 0 16 0 20 0 ? I guess it is all about operators precedence, but after thinking a while I can't realize what's wrong with my interpretation. Can you explain it a little bit?

#include <stdio.h>

int main(void)
{
    int tab[10] = {2,4,6,8,10,14,16,18,20};
    int *pi, i;
    for(pi = tab; ++pi < tab+9;)
    {
        *pi++ = 0;
        *pi *= 2;
    }

    for(int i=0; i<10; i++)
        printf("%d ", tab[i]);

    return 0;
}

Solution

  • The first thing that the for loop does is point pi at tab, i.e. pi=&tab[0] So pi is pointing at the number 2. The next piece of code to be executed is the for loop's "condition" statement ++pi < tab+9. This first increments pi (so it's now pointing at the number 4 in tab[1]) and checks whether it's still pointing at a member of tab earlier than the final 20.

    In the body of the for loop, the line *pi++ = 0; first stores a 0 at the address pointed to by pi (which means that tab[1] is now 0 rather than 4) and then (post-) increments pi to point at tab[2], which is 6. Then the line *pi *= 2; doubles the value pointed to by pi, so tab[2] becomes 12.

    The next thing that happens is a re-evaluation of the for loop's conditional statement (since its iteration statement is empty): pi is incremented and checked.

    The rest of the iterations are fairly uneventful. The final state of tab is that the first member is unchanged, members with an odd index are zero, and other members are doubled from their initial value.

    General advice regarding operators and precedence: one of two situations is almost always the case. The first is that you and the compiler don't agree on the order in which the operators in your code will be applied—in other words your code doesn't do what you expect. The second is that you understand perfectly what the compiler is going to do, but the programmer reading your code does not—in other words your code doesn't do what they expect. Fortunately, both situations can be mitigated by adding parentheses to remove any doubt.