Tomasz Różański
11 posts
Episode 32 PSA: Prefix and postfix pointer incrementation and decrementation
Edited by Tomasz Różański on 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:

 1 --*TileMap 

 1 ++*TileMap 

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

 1 *TileMap-- 

 1 *TileMap++ 

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:

 1 (*TileMap)-- 

 1 (*TileMap)++ 

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
135 posts / 1 project
Annotator, supper gatherer and slammer of thunderous high fives
Episode 32 PSA: Prefix and postfix pointer incrementation and decrementation
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:

 1 2 *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.