3

I'm trying to understand why all following three cases resulted in different output on Visual C++ compiler

Program 1

  i = 0;
  while ( i < 100)
  {
      printf( "%d: %d\n", array1[i], array2[i]);
      i++;
  }

Program 2

  i = 0;
  while ( i < 100)
  {
      printf( "%d: %d\n", array1[i], array2[i++]);
  }

Program 3

  i = 0;
  while ( i < 100)
  {
      printf( "%d: %d\n", array1[i++], array2[i]);
  }

As per my understanding, I was expecting that increment operator will increment the value of i after the expression has been evaluated. Initially I thought all three would lead to same output but after seeing output, I was expecting atleast Program 1 and Program 2 output should be same.

However, output was different in all three cases. Please correct me what I am missing here.

Rohit
  • 6,365
  • 14
  • 59
  • 90
  • 3
    This is invoking undefined behavior, the evaluation order of the function parameters is unspecified. The second problem is that if you modify a variable within a sequence point you are only allowed to read the previous value to determine the new value. – Shafik Yaghmour Sep 05 '13 at 02:38
  • 2
    I was not aware of sequence points. Thanks for pointing to right direction. Marked as dupilicate. – Rohit Sep 05 '13 at 02:42

0 Answers0