C / C ++后增加多个 [英] 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++))
这很好,但是我如何可以将位置递增2或4?有没有办法我可以得到 + =
运算符后递增,是吗?
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.
结论:
不要这样做。这只是一个坏主意,因为这是一种生成不可维护的代码的东西。但是...它确实很容易将任何预递增运算符转换为后递增运算符。
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.
推荐答案
好吧,我在编辑中回答了我的问题...基本上我想要的是一个单独的表达式,但是具有增加任意量的副作用。这里有一些宏。
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)
这篇关于C / C ++后增加多个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!