7

我的印象是后增量(或前增量)只能在相等(=)的右侧完成。但我能够编译下面的代码。你能帮我理解这个特定的代码,尤其是下面的代码。来源:http ://www.ibm.com/developerworks/library/pa-dalign/

*data8++ = -*data8;


void Munge8( void *data, uint32_t size ) {
    uint8_t *data8 = (uint8_t*) data;
    uint8_t *data8End = data8 + size;

    while( data8 != data8End ) {
        *data8++ = -*data8;
    }
}
4

5 回答 5

7

所以,我相当确定这是未定义的行为。除了最后的分号之外没有序列点:

    *data8++ = -*data8;

如果 data8 等于 0x20,是否等于:

    *(0x20) = -*(0x20);

或者

    *(0x20) = -*(0x24);

因为没有办法做出这个决定,(因为你在读取它两次时编辑了一个变量,没有交错序列点),这是未定义的行为


我们可以讨论下面这段代码的作用。这可能是上述代码的意图。

while( data8 != data8End ) {
    *data8 = -*data8;
    data8++;
}

你在这里做的事情希望更简单。您正在获取输入数组,并查看它,因此它是一系列 8 位数字。然后,就地,你否定每一个。

于 2012-06-18T18:38:25.673 回答
4

Your impression is wrong, I guess. You can definitely do things like:

*a++ = *b++;

In fact, that's often how strcpy is implemented. You can even have the post- or pre-increments without an = at all:

a++;
于 2012-06-18T18:26:20.923 回答
2

++ is applied to the pointer, not to the value pointed by data8.

*data8++ = -*data8;

is equivalent to:

*data8 = -*data8;
data8++;

EDIT:
After reading the C99 standard 6.5 and Annex C, it's clear = is not a sequence point. Standard mentions only &&, ||, , and ?.

Since, data8 is modified on both sides of = which no sequence point and standard doesn't mandate whether RHS should be evaluated first Or LHS should be evaluated first, I am convinced this is Undefined Behaviour.

Any good reason why assignment operator isn't a sequence point?

This above post discusses = being not a sequence point and is quite related here.

于 2012-06-18T18:26:35.767 回答
1

There's no reason why post-increment cannot be done on the left-hand side of the assignment operator. A post-increment operator simply returns a temporary copy of the object in its previous state, and that temporary object (in this case a pointer) can have operations performed on it.

Now, in the case of:

*data8++ = -*data8;

because of operator ordering, the data8 pointer will first be post-incremented, returning a copy of the previous pointer value. That previous pointer value will then be dereferenced and assigned the results of the expression on the right-hand side of the assignment operator.

Edit: As others have pointed out, you're modifying the contents of data8 by reading more than once while writing to that memory location without a sequence point, so this is undefined behavior.

于 2012-06-18T18:26:26.500 回答
0

我觉得

*data8++ = -*data8;

相当于

*data8 = - *(data8 + 1);

数据8 = 数据8 +1

于 2015-08-14T09:21:55.413 回答