C/C 后增量超过 1

新手上路,请多包涵

我正在从缓冲区读取字节。但有时我正在阅读的是一个单词或更长的内容。

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

这很好,但我怎样才能将位置增加 2 或 4?我无法让 += 运算符进行后增量,是吗?

原因是,我想要评估这个可怕的大表达式,同时增加位置变量。

我想我想出了自己的解决方案。我很确定它有效。但是每个人都会讨厌它,因为这不是可读的代码。

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

在对其进行一些测试以确保它做正确的事情后,我将把它变成一个宏。

综上所述:

不要这样做。这只是一个坏主意,因为这是生成无法维护的代码的那种事情。但是……事实证明,将任何预递增运算符转换为后递增运算符确实非常容易。

原文由 Steven Lu 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 355
2 个回答

好吧,我确实在编辑中回答了我的问题……基本上我想要的是一个表达式,它的计算结果为原始值,但具有增加任意数量的副作用。这里有一些宏。

 #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)

原文由 Steven Lu 发布,翻译遵循 CC BY-SA 2.5 许可协议

虽然,我不会推荐这个解决方案,但如果你不想在你的代码中更改这一行:

 read_ptr(buffer+(position++));

而且您仍然希望将 position 后增量 2,然后将 位置 定义为 Index position(2); 其中类型 Index 在这里定义,并且还显示了用法

struct Index
{
    int step;
    int value;
    Index(int s=1, int v=0): step(s), value(v) {}
    Index operator++(int)
    {
       Index prev(step, value);
       value += step;
       return prev;
    }
    operator int() { return value; }
};

int main() {
        char arr[] = "1234567890" ;

        cout <<"Increment by 2" <<endl;
        Index i2(2); //increment by 2
        cout << *(arr + (i2++)) << endl;
        cout << *(arr + (i2++)) << endl;
        cout << *(arr + (i2++)) << endl;
        cout << *(arr + (i2++)) << endl;

        cout <<"Increment by 3" <<endl;
        Index i3(3); //increment by 3
        cout << *(arr + (i3++)) << endl;
        cout << *(arr + (i3++)) << endl;
        cout << *(arr + (i3++)) << endl;
        cout << *(arr + (i3++)) << endl;
        return 0;
}

输出:

 Increment by 2
1
3
5
7
Increment by 3
1
4
7
0

工作示例:http: //ideone.com/CFgal

注意: 我仍然不会在现实生活项目中建议这个解决方案。这更像是拼图:D

原文由 Nawaz 发布,翻译遵循 CC BY-SA 2.5 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题