C/C++ Post-increment by more than one

Steven Lu picture Steven Lu · Mar 19, 2011 · Viewed 16.3k times · Source

I'm reading bytes from a buffer. But sometimes what I'm reading is a word or longer.

// assume buffer is of type unsigned char *
read_ptr(buffer+(position++))

That's fine but how can I post-increment position by 2 or 4? There's no way I can get the += operator to post-increment, is there?

Reason is, I have this big awful expression which I want to evaluate, while at the same time incrementing the position variable.

I think I came up with my own solution. I'm pretty sure it works. Everyone's gonna hate it though, since this isn't very readable code.

read_ptr(buffer+(position+=4)-4)

I will then make this into a macro after testing it a bit to make sure it's doing the right thing.

IN CONCLUSION:

Don't do this. It's just a bad idea because this is the sort of thing that generates unmaintainable code. But... it does turn out to be quite easy to convert any pre-incrementing operator into a post-incrementing one.

Answer

Prasoon Saurav picture Prasoon Saurav · Mar 19, 2011

how can I post-increment position by 2 or 4?

You can't post-increment a variable by 2 or 4 but you can use the following (in your case)

read_ptr(buffer+position); position += 2;