Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "*ptrInt ++" do?

I'm implementing a template pointer wrapper similar in functionaltiy to boost::shared_ptr.

I have a pointer to an integer ptrInt.

What I want to do: Increment the integer ptrInt points to.

My initial code was this: *ptrInt ++;, although I also tried the same using (*ptrInt) ++;

Apparently, however, this doesn't seem to do what I expected it to. In the end I got it working using *ptrInt += 1;, however I'm asking myself:

  • What exactly does *ptrInt ++; do?
  • Is there a more elegant solution to using *ptrInt += 1;?
like image 865
Klitschko Avatar asked Jul 02 '11 20:07

Klitschko


1 Answers

*p++    // Return value of object that p points to and then increment the pointer
(*p)++  // As above, but increment the object afterwards, not the pointer
*p += 1 // Add one to the object p points to

The final two both increment the object, so I'm not sure why you didn't think it worked. If the expression is used as a value, the final form will return the value after being incremented but the others return the value before.

x = (*p)++; // original value in x

(*p)++;
x = *p;     // new value in X

or

x = ++*p;   // increment object and store new value in x
like image 84
DigitalRoss Avatar answered Sep 23 '22 12:09

DigitalRoss