1

I couldn't figure out the reason for the output I got:-

    int ar[5] = {1, 3, 5, 7, 9};
    int *p = ar;
    printf("%d\t%d\n", *p, *(p++));

output: 3 1

but i expected : 1 3 as p points to the 1st element and p++ points to the 2nd element.

user3248186
  • 1,518
  • 4
  • 21
  • 34

3 Answers3

7

Order of evaluation for function arguments is unspecified.

pmr
  • 58,701
  • 10
  • 113
  • 156
  • True but that's not the main problem...what we have is UB here. – P.P Jan 29 '14 at 10:17
  • @BlueMoon Paragraph 5/4 `Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression.` I only see one modification, but I might be wrong here. – pmr Jan 29 '14 at 10:18
0

order of evaluation from right to left evaluate *(p++) first and increase the address then evaluate *p which now point to next element.Try *(p+1) instead of it.

Jayesh Bhoi
  • 24,694
  • 15
  • 58
  • 73
  • i know that *(p+1) gives 3, but i wanna know what's wrong with my code – user3248186 Jan 29 '14 at 10:38
  • nothing wrong in your code! It just parameter evaluation result and note that parameter evalution is undefined. For looking more comment on this topic go – Jayesh Bhoi Jan 29 '14 at 11:01
0

This gives a nice example how order of evaluation for function arguments is not granted.

Parameter evaluation order before a function calling in C

Community
  • 1
  • 1
Sandstorm
  • 1
  • 1