running this code:
#include <stdio.h>
int main() {
int x[]={20,30};
int *p=x;
++*p++;
printf("%d %d\n",x[0],*p);
return 0;
}
the output is 21 30 which is something that doesn't make sense to me because according to C operator precedence the postfix increment comes first though if that was the case in my opinion the output should be 20 31.For the record i am new to programming and it really seems that i cant get the hang of it so sorry if this question is stupid :)
From the C++ Standard (the same is valid for the C Standard)
5.2 Postfix expressions 1 Postfix expressions group left-to-right.
Postfix expressions and p++
is a postfix expression have higher priority than unary expressions.
The C++ Standard
5.3 Unary expressions 1 Expressions with unary operators group right-to-left.
In this expression ++*p
there are two unary subexpressions: *p
and ++( *p )
So the whole expression can be written like
++( *( p++ ) );
Take into account regarding the postfix expression ++ that (now it is the C Standard)
6.5.2.4 Postfix increment and decrement operators
2 The result of the postfix ++ operator is the value of the operand. As a side effect, the value of the operand object is incremented (that is, the value 1 of the appropriate type is added to it).
Let's consider the result of the expression statement
++( *( p++ ) );
subexpression p++
has the value of its operand that is the address of type int *
of the first element of the array. Then due to the dereferencing the expression *( p++ )
yields the lvalue of the first element of the array that is x[0]
and then its value is increased. So the first element of the arry now has the value 21.
At the same time the postfix increment incremented the pointer p
as its side effect (see the quote above from the C Standard). Its now points to the second element of the array.
Thus the output will be
21 30