1

I've got a strange C++ code:

#include <iostream>
#include <stdio.h>
using namespace std;
int main() {
     int tab[][2] = { {1,2}, {3,4}, {5,6} };
     int *a = tab[0];
     printf( "%d %d %d", *a++, *a++, *a++ );
     return 0;
}

And I've got a question: why the output is 3 2 1. Could you explain this pointer arithmetics? Thanks.

Michał Wiatr
  • 481
  • 4
  • 21
  • 3
    It's undefined behaviour. – chris Apr 07 '13 at 20:38
  • 1
    Duplicate of 1m+ questions – Ed S. Apr 07 '13 at 20:39
  • I suspect you are seeing first dimension, second dimension, first value. Should be easy to confirm by changing dimensions and values. Agree with Chris- this is compiler dependent and undefined. – Floris Apr 07 '13 at 20:41
  • 1
    @Floris: No, you cannot reason about it. Order of function argument evaluation is *unspecified*. Modifying a variable more than once before encountering a sequence point results in *undefined behavior*. The terms *unspecified* and *undefined* have different meanings. – Ed S. Apr 07 '13 at 20:42
  • @Floris: Yes, it does. The commas in a function call are *not* examples of the comma operator, i.e., they are not sequence points. – Ed S. Apr 07 '13 at 20:42
  • OK - I was wrong, @EdS. is right. My apologies. – Floris Apr 07 '13 at 20:50

0 Answers0