Handmade Hero » Forums » Game » Episode 32 PSA: Prefix and postfix pointer incrementation and decrementation
Rosto
Tomasz Różański
9 posts
#11334 Episode 32 PSA: Prefix and postfix pointer incrementation and decrementation
7 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:

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!
Miblo
Matt Mascarenhas
105 posts
2 projects

Annotator, supper gatherer and slammer of thunderous high fives

#11335 Episode 32 PSA: Prefix and postfix pointer incrementation
7 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:

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.