Reputation: 105
This piece of code:
int scores[] {1,2,3,4};
int *score_ptr {scores};
//let's say that initial value of score_ptr is 1000
std::cout<<*score_ptr++;
produces the output:
1
As *
and ++
have same precedence and then associativity is from right to left shouldn't we apply ++
operator first that is to increase the pointer first and then *
(dereference) it?
So accordingly score_ptr
will be increased to 1004
and then dereferencing it will give the second element of scores which is 2
.
How and why does this give me output of 1
instead of 2
?
Upvotes: 2
Views: 336
Reputation: 23802
The increment will happen first, it has higher precedence, it's equivalent to *(score_ptr++)
, but it's a post-increment, this means it will only happen after the dereferenced pointer is used, i.e. the expression reaches ;
.
If you use
std::cout << *++score_ptr;
Then you have a pre-increment, here it will happen beforehand, the pointer will be incremented before the value is used and the output will be 2
. Equivalent to *(++score_ptr)
.
Note that it's allways a good idea to use parentheses, it will make the code clearer and will avoid missinterpretations.
Upvotes: 1
Reputation: 172934
As
*
and++
have same precedence
No, postfix operator++
has higher precedence than operator*
; then *score_ptr++
is equivalent to *(score_ptr++)
. Note that the postfix operator++
would increment the operand and return the original value, then *(score_ptr++)
would give the value 1
.
The result is prvalue copy of the original value of the operand.
On the other hand prefix operator++
returns incremented value. If you change the code to *++score_ptr
(which is equivalent to *(++score_ptr)
) then the result would be 2
(which might be what you expected).
Upvotes: 7