Klitschko
Klitschko

Reputation: 81

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:

Upvotes: 8

Views: 418

Answers (8)

Frigo
Frigo

Reputation: 1724

(*ptr)++ should do it, unless you are using its value right away. Use ++*ptr then, which is equivalent to ++(*ptr) due to right-to-left associativity.

On a side note, here is my smart pointer implementation, perhaps it can help you in writing your own.

Upvotes: 1

kilotaras
kilotaras

Reputation: 1419

*ptrInt ++ will

  1. increment ptrInt by 1

  2. dereference old value of ptrInt

and (*ptrInt) ++ as well as *ptrInt += 1 will do what you want.

See Operator Precedence.

Upvotes: 3

liaK
liaK

Reputation: 11648

The more elegant way is whatever you tried before. i.e (*ptrInt) ++;

Since, you aren't satisfied with that, it might be because of the post - increment.

Say, std::cout<<(*ptrInt) ++; would have shown you the un-incremented value.

So, try giving ++(*ptrInt); which might behave as you expected.

Upvotes: 0

Antti
Antti

Reputation: 12479

You want (*ptrInt)++, which increments the object, which generally does the same as *ptrInt += 1. Maybe you have overloaded the += operator, but not the ++ operators (postfix and prefix increment operators)?

Upvotes: 0

Andrei
Andrei

Reputation: 5005

The expression is evaluated using the rules for operator precedence.

The postfix version of ++ (the one where ++ comes after the variable) has a higher precedence than the * operator (indirection).

That is why *ptr++ is equivalent to *(ptr++).

Upvotes: 0

Karoly Horvath
Karoly Horvath

Reputation: 96258

*ptrInt++ in your case does increment the pointer, nothing more (before that it fetches the value from the location at throws it away. of course if you use it in a more complex expression it will use it)

(*ptrInt)++ does what you are looking for.

Upvotes: -1

Alok Save
Alok Save

Reputation: 206508

*ptr++ equivalent to *(ptr++)

Upvotes: 4

DigitalRoss
DigitalRoss

Reputation: 146053

*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

Upvotes: 9

Related Questions