5

我正在阅读以下代码:

if( (i%2) == 0 ){ 
    *d = ((b & 0x0F) << 4); 
}
else{
    *d++ |= (b & 0x0F); 
};

我正在专门查看该else声明,并想知道这是按什么顺序发生的?我没有常规的 C 编译器,因此无法对此进行测试。当我们在执行*d++ |= (b & 0x0F);时,这是按什么顺序发生的?

4

7 回答 7

11

The ++ is applied on the pointer d, not on the lvalue that is being assigned to, *d.

If you really want to, you can think of it like this:

  1. The value of b is bitwise-AND:ed with the constant 0x0f
  2. The resulting bit pattern is bitwise-OR:ed into the value that d points at.
  3. The pointer d is incremented to point at the next value.
于 2010-05-19T13:08:50.200 回答
5

d++ returns the value d had before it was incremented. This is then dereferenced by the *, and that location is what the |= is performed on. So the data at the location prior to incrementing d will have (b & 0x0F) ored into it.

In general, if the order of operations in a line of code is not clear at a glance, refactor the line into its constituent operations until it is. Generated code does not become any faster or more compact simply from squeezing lots of operations onto one line of C! There is no good reason to sacrifice comprehensibility in this way. Replace the line with

*d |= (b & 0x0F); 
d++;
于 2010-05-19T13:11:30.850 回答
2

First the right part of |= is executed, then the *d |= assignment is done, then d is incremented. Usually when you have code that causes questions like that you should just rewrite it for the sake of clarity.

于 2010-05-19T13:09:50.480 回答
2

++之前会发生|=。赋值运算符位于优先级图表的底部。

于 2010-05-19T13:13:08.047 回答
0

++ is done first. However post-increment (i.e. d++ here) is equivalent to this (temp=d, d++, temp).

于 2010-05-19T13:12:16.637 回答
0

根据http://www.cppreference.com/wiki/operator_precedence

它将评估 (b & 0x0F) 然后对其应用 |= 并将其分配给 *b,最后增加 *b 指向的值。

于 2010-05-19T13:14:09.440 回答
0

表达式*d++ |= (b & 0x0F)分解如下:

  1. 表达式*d++b & 0x0F每个都被计算一次(没有指定它们被计算的顺序;编译器可以自由地b & 0x0F在之前计算,*d++因为结果不依赖于计算发生的顺序);
  2. 的结果与;的结果进行(b & 0x0F)位或运算。*d++
  3. 按位或运算的结果存储到 d 最初指向的位置;
  4. 在所有这一切的某个时刻, 的值d会更新。

表达式*d++被解析为*(d++); 即您正在取消引用表达式的结果d++。表达式d++计算为 的当前值,并且在下一个序列点之前的d某个未指定d点(在本例中为语句的结尾),更新 的值。更新的副作用d不必立即应用;它可以在分配之前或之后发生。

于 2010-05-19T13:42:08.233 回答