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?

2
  • 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
    Commented Jun 24, 2011 at 17:45
  • @Damon: The behaviour is not undefined. It's unspecified. See stackoverflow.com/questions/621542/….
    – orlp
    Commented Jun 24, 2011 at 17:48

4 Answers 4

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".

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.

3
  • @Damon: The behaviour is not undefined. It's unspecified. See stackoverflow.com/questions/621542/….
    – orlp
    Commented Jun 24, 2011 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
    Commented Jun 24, 2011 at 17:49
  • @user618541: You're teacher is wrong. It might be true for one compiler, but not for Standard C.
    – orlp
    Commented Jun 24, 2011 at 17:50
0

Undefined behaviour, output may various on different compiler.

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.