C / C ++后递增多个

时间:2011-03-19 06:47:11

标签: c++ c operators post-increment

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

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

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

原因是,我有一个非常糟糕的表达式,我想要评估,同时增加位置变量。

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

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

然后我会在测试它之后将其变成一个宏,以确保它正在做正确的事情。

结论:

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

7 个答案:

答案 0 :(得分:3)

  

如何将position后加2或4?

您不能将变量后加2或4,但您可以使用以下(在您的情况下)

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

答案 1 :(得分:3)

+ =运算符将是一个单独的语句(不是post或pre increment)。您可以使用以下行:

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

答案 2 :(得分:3)

你没有;你把它分成了不止一行。这里没有理由把所有东西都塞进一行。

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

答案 3 :(得分:3)

虽然,我不建议使用此解决方案,但如果您不想在代码中更改此行:

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

答案 4 :(得分:1)

如果position是指向int16int32的指针,则递增它会分别增加2或4。

答案 5 :(得分:1)

在C ++中,您可以轻松编写一个函数来执行后期样式的双增量:

template <typename T>
T inc2(T &t) {
    T r(t);
    ++t; // or t++ if you want to respect inconsistently-overloaded operators,
    ++t; // but I wouldn't bother.
    return r;
}

read_ptr(buffer+inc2(position))

在C中,它稍微有些尴尬:

size_t inc2(size_t *s) { // or whatever type you're using
    size_t r = *s;
    (*s) += 2;
    return r;
}

read_ptr(buffer+inc2(&position))

您可以通过将其作为附加函数参数或C ++案例中的附加模板参数来覆盖4个案例。

还有第二个问题,是否值得在C ++或C中使用这种编程方式,在一个语句中你可以做很多事情。避免副作用可以使代码更容易理解,即使它出现的时间更长。

答案 6 :(得分:0)

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

#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)
相关问题