2
int main(){
    int a[3]={1,10,20};
    int *p=a;
    printf("%d %d " ,*++p,*p);
    return 0;
}

The output to the code above is 10 1 on a gcc compiler.

I understand that *++p increments p and dereferences the new value. But since p has been incremented, why does *p return 1 instead of 10?

Divij
  • 878
  • 2
  • 9
  • 18
  • This code has undefined behaviour. While it is clear what `*++p` will do (first increment, then dereference), it is not clear whether this or the following `*p` is evaluated first. As such, the output of your program is... kind of random (or more specifically, compiler-specific). It is therefore not possible to "understand" the code. – Damon Jun 24 '11 at 17:45
  • @Damon: The behaviour is __not__ undefined. It's unspecified. See http://stackoverflow.com/questions/621542/compilers-and-argument-order-of-evaluation-in-c/621548#621548. – orlp Jun 24 '11 at 17:48

4 Answers4

7

It's unspecified behaviour in what order function argument expressions are evaluated. Some compilers might use left-to-right, some right-to-left, and some might do a different evaluation order depending on the situation for optimalization. So in your case *p gets evaluated before *++p which results in your "weird output".

orlp
  • 112,504
  • 36
  • 218
  • 315
2

The comma between *++p and *p does not denote a sequence point, so this is undefined unspecified behavior. The compiler is free to evaluate *p before *++p.

Jim Lewis
  • 43,505
  • 7
  • 82
  • 96
  • @Damon: The behaviour is __not__ undefined. It's unspecified. See http://stackoverflow.com/questions/621542/compilers-and-argument-order-of-evaluation-in-c/621548#621548. – orlp Jun 24 '11 at 17:48
  • @jim Lewis: I am the beginer in c.But My Teachers told that in C language the expressions are evaluated from right to left.(i.e) first *p is evaluated then *++p. – Aravindhan Jun 24 '11 at 17:49
  • @user618541: You're teacher is wrong. It might be true for one compiler, but not for Standard C. – orlp Jun 24 '11 at 17:50
0

Undefined behaviour, output may various on different compiler.

secmask
  • 7,649
  • 5
  • 35
  • 52
0

Apparently, your arguments are being evaluated in reverse order (last to first) so *p is evaluated first and it will return 1.

As others have pointed out, the standard does not dictate what order the arguments are evaluated and so this behavior may or may not look the same with other compilers.

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466