-4

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)++;
}
halfer
  • 19,824
  • 17
  • 99
  • 186
Ava
  • 27
  • 2
  • 12
    Look at [operator precedence](http://en.cppreference.com/w/cpp/language/operator_precedence). – Jarod42 Mar 08 '17 at 18:36
  • 2
    It would dereference the pointer, and then increment it. You should invest in [a good C++ book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list?lq=1) – Rob K Mar 08 '17 at 18:37
  • `*xPtr++` would be `*(xPtr++)` – Jarod42 Mar 08 '17 at 18:39
  • `void foo int * xPtr { *xPtr ++; }` does not compile. ;-) – chux - Reinstate Monica Mar 08 '17 at 18:41
  • (whether or not it compiles/runs)Adding parentheses adds code readability. – Max Mar 08 '17 at 18:42
  • 1
    _@Ava_ Welcome to Stack Overflow. Please take the time to read [The Tour](http://stackoverflow.com/tour) and refer to the material from the [Help Center](http://stackoverflow.com/help/asking) what and how you can ask here. – πάντα ῥεῖ Mar 08 '17 at 18:48

3 Answers3

0

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

Manetho
  • 147
  • 1
  • 3
0

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.

Sumeet
  • 8,086
  • 3
  • 25
  • 45
0

(*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.

John Bode
  • 119,563
  • 19
  • 122
  • 198