c++coperatorspost-increment

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


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.


Solution

  • Well, I did answer my question in the edit... Basically what I wanted was a single expression which evaluates to the original value but has a side effect of incrementing by an arbitrary amount. Here are some macros.

    #define INC(x,inc) (((x)+=(inc))-(inc))
    #define INC2(x) INC(x,2)
    #define INC4(x) INC(x,4)
    #define INC8(x) INC(x,8)