What is the purpose of the parentheses in the following piece of code? What would be happening if the parentheses were not there? Sorry, I am new to C++.
void foo(int * xPtr) {
(*xPtr)++;
}
What is the purpose of the parentheses in the following piece of code? What would be happening if the parentheses were not there? Sorry, I am new to C++.
void foo(int * xPtr) {
(*xPtr)++;
}
With the parentheses, you increment the object the pointer is referencing, without them, you are incrementing the pointer to the next memory address and THEN dereferencing it (which in this case would do nothing).
If parentheses are not there then you are basically modifying the memory address stored inside xPtr
and then dereferencing the pointer. So clearly this is not what is desired.
Say we want the value stored at memory location 1000
to be incremented, but
*xPtr++;
results in incrementing the memory location by 4 and then,value at memory location 1004
is accessed, assuming size of integer on the machine is 4 bytes
.
(*xPtr)++
will increment the thing xPtr
points to.
Postfix ++
has higher precedence than unary *
; without parentheses, the code would be parsed as *(xPtr++)
- you're incrementing xPtr
, not the thing xPtr
points to.