1

There is the following C code:

#include <stdio.h>

int main ()
{
    int a[5] = {0, 1, 2, 3, 4};
    int* a_p = a;
    float x = 1.5;

    while(x > (*a_p++))
    {
        printf("*a_p = %d\n", *a_p);
    }

    printf("*a_p = %d", *a_p);
    return 0;
}

The question would be which is the result of the final printf statement? I would judge that the order is:

1) inside while, a_p address is incremented => *a_p is 1 (a[1])

2) 1.5 is compared with 1

3) inside while, a_p address is incremented again => *a_p is 2 (a[2])

4) 1.5 is compared with 2

5) 2 is printed for *a_p

I have tried with 3 compilers and the result is 3. Why 3 is the correct result? Is first done the comparison and then the pointer is incremented meaning that at step 4 from above, after the comparison is done, *a_p is 3? Is this always the behavior (is this behavior defined) or is compiler dependent?

Adi S.
  • 53
  • 1
  • 10
  • 1
    `a_p` is incremented *after* the comparison, regardless of the result of the comparison. – Weather Vane Feb 03 '18 at 18:27
  • Tried doing some research? See the second answer to https://stackoverflow.com/questions/4445706/post-increment-and-pre-increment-concept for example. – GhostCat Feb 03 '18 at 18:31
  • I have researched it quite a lot, but I was focused of "order of evaluation". I have completely missed the *pre* and *post* increment. Thanks. – Adi S. Feb 03 '18 at 18:47

1 Answers1

3

Yes that's how post increment works. The while condition is true for 0th and 1th index but when it evaluates to false - the pointer value is already increased as a result it points to index 4 having value 3.

*p++ the value of it will be *p where this p is the old one which is not incremented. Same happens with a_p is here - last time when it is compared the value *a_p++ is 2 but the new value of a_p is pointing to the 4th index. Loop ends and 3 is printed.

user2736738
  • 30,591
  • 5
  • 42
  • 56