1

I'm trying to understand why do i have this output.

a[0]: 5, a[1]: 5, ptr: 5

From this little program.

#include <stdio.h>

int main() {
    int a[2] = {5, 10};
    int *ptr = a;

    *ptr = *(ptr++);

    printf("a[0]: %d, a[1]: %d, ptr: %d\n", a[0], a[1], *ptr);

    return 0;
}

The part that I don't understand is.

*ptr = *(ptr++);

Because according to me what should happen is that ptr should point to 10, and nothing more, because ++ postfix should increment ptr after the allocation, so according to me this should allocate the value of a[0] to a[0] (which would not affect anything) and after this ptr should be pointing to the 10 on a[1], but what really happens is that at the end a[1] is also 5, can someone explain this to me?.

Patricio Sard
  • 2,092
  • 3
  • 22
  • 52
  • well, for me it prints `a[0]: 5, a[1]: 10, ptr: 10` – Sourav Ghosh Nov 30 '14 at 23:08
  • possible duplicate of [Why are these constructs (using ++) undefined behavior?](http://stackoverflow.com/questions/949433/why-are-these-constructs-using-undefined-behavior) – 2501 Nov 30 '14 at 23:13

1 Answers1

5

What you are seeing is undefined behavior. The language does not guarantee whether the LHS is evaluated first or the RHS is evaluated first. A platform can choose which side gets evaluated first.

Looks like in your platform, the RHS is evaluated first.

The value of RHS, is 5. The side effect is ptr to point to a[1].

Then, it is assigned to *ptr, which is a[1].

Caution This style of programming is strongly discouraged in the real world since the compiler can do anything it chooses to. See http://en.wikipedia.org/wiki/Undefined_behavior.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • 1
    gcc warns us when you use the right flags `gcc -W -Wall test.c` `test.c:7: warning: operation on ‘ptr’ may be undefined` – Alex Strate Nov 30 '14 at 23:11
  • 1
    suggest re-wording the text to clarify that anything can happen (i.e. it's not merely unspecified behaviour) - OP is new and may not be aware of the ramifications of UB – M.M Nov 30 '14 at 23:37