9

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

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

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

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

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

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

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

综上所述:

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

4

7 回答 7

4

我怎样才能增加position2 或 4?

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

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

于 2011-03-19T06:49:34.133 回答
4

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

read_ptr(buffer+(position++));

并且您仍然希望后递增position2,然后将位置定义为此处定义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

于 2011-03-19T07:09:01.640 回答
3

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

func(buffer + position); position += 2;
于 2011-03-19T06:50:02.387 回答
3

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

read_ptr( buffer + position );
position += n;
于 2011-03-19T06:50:46.100 回答
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)
于 2011-03-22T04:30:34.937 回答
1

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

于 2011-03-19T06:50:36.460 回答
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 中追求这种编程风格,你在一个语句中做这么多。避免副作用可以使代码更容易理解,即使它出现的时间更长。

于 2011-03-19T11:53:01.123 回答