-2
 print(int*a,int*b,int*c,int*d,int*e){
   printf("\n%d %d %d %d %d %d",*a,*b,*c,*d,*e);
 }

 main(){
  static int arr[]={97,98,99,100,101,102,103,104};
  int *ptr=arr+1;
  print(++ptr,ptr--,ptr,ptr++,++ptr);
  return 1;
  }

O/P: 100 100 100 99 100 (some -ve values) on GCC & turbo C

According to my understanding, the ptr points to 98 first, then ++ptr is passed which makes it to point 99.How in the world it prints 100? Even then, it does not decrements the ptr till 3rd argument and prints it again.What's going on?

joey rohan
  • 3,505
  • 5
  • 33
  • 70
  • 1
    This invokes undefined behaviour, so it can be whatever โ€“ Sami Kuhmonen Jul 20 '15 at 18:15
  • 1
    Function arguments [aren't evaluated in a specified order](http://stackoverflow.com/questions/376278/parameter-evaluation-order-before-a-function-calling-in-c), left-to-right or otherwise. This is one of many possible outputs from such a program - it's undefined behavior, and would likely be different on different compilers. No reason to ask *why*, since you can't rely on it. The "random" last number is due to the extra `%d` in your `printf()`, with no matching parameter. โ€“ Paul Roub Jul 20 '15 at 18:15
  • 1
    Just for fun, the answer using clang is `99 99 98 98 100` and the answer using gcc is `100 100 100 99 100`. So it just goes to show that compilers do take advantage of undefined behavior in different ways. โ€“ Matt Habel Jul 20 '15 at 18:17

2 Answers2

1

The above code will result multiple warnings which may lead to undefined behaviour in multiple systems

print(++ptr,ptr--,ptr,ptr++,++ptr);

multiple unsequenced modifications to 'ptr' [-Wunsequenced]

because in my compiler it is giving output as below :
99 99 98 98 100 0
Sohil Omer
  • 1,171
  • 7
  • 14
1

Whow ! Your print function has 6 %d, and you only pass 5 int values => undefined behaviour

You are modifying more than once ptr in a single call (*) => undefined behaviour

I would say that the compiler can do anything without you can say it is wrong ...

(*) the order of the operations in a single instruction is undefined (except some explicit cases) : 6.5 ยง2-3 : Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. and Except as specified later (for the function-call (), &&, ||, ?:, and comma operators), the order of evaluation of subexpressions and the order in which side effects take place are both unspecified.

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252