Handmade Hero»Forums»Game»Episode 32 PSA: Prefix and postfix pointer incrementation and decrementation
Tomasz Różański
9 posts
Episode 32 PSA: Prefix and postfix pointer incrementation and decrementation
3 years, 3 months ago Edited by Tomasz Różański on March 16, 2017, 8:59 p.m. Reason: typo in the title
I was following episode 32 this morning. I typed all the changes Casey has made to the coordinates system, checking the game state after every second compilation. At some point my avatar stopped moving between the rooms but I didn't think too much about it: Casey changed so many things, surely something must be broken at this point. At the end of the coding session, however, Casey's code worked flawlessly, unlike mine. WTF?!

An hour later, I knew what was my mistake.

In RecanonicalizeCoord() function Casey used following two lines for changing the TileMap index:



but because I prefer the postfix notation, I casually typed:



Turns out this syntax increments only the pointer itself, not the referenced value, as was intended. If, like me, you would like to use postfix notation, here's the proper syntax:



They say that every bug is an opportunity to learn something new. I lost an hour but I'm a better programmer now. Totally worth it!
Matt Mascarenhas
141 posts / 2 projects

Annotator, supper gatherer and slammer of thunderous high fives

Episode 32 PSA: Prefix and postfix pointer incrementation
3 years, 3 months ago
It may be worth mentioning that pre- / post-incrementing isn't a stylistic choice: they do functionally different things when we assign to them. Take these two assignments:

*OutPtr++ = '2';
*++OutPtr = '2';

The first one will assign '2' to the value pointed to by OutPtr and then increment OutPtr.
The second will increment OutPtr and then assign '2' to the new value pointed to by OutPtr.

Cheers for pointing out (*Ptr)++ / (*Ptr)-- being a way to {in,de}crement the value. I hadn't learnt that.