我正在阅读以下代码:
if( (i%2) == 0 ){
*d = ((b & 0x0F) << 4);
}
else{
*d++ |= (b & 0x0F);
};
我正在专门查看该else
声明,并想知道这是按什么顺序发生的?我没有常规的 C 编译器,因此无法对此进行测试。当我们在执行*d++ |= (b & 0x0F);
时,这是按什么顺序发生的?
我正在阅读以下代码:
if( (i%2) == 0 ){
*d = ((b & 0x0F) << 4);
}
else{
*d++ |= (b & 0x0F);
};
我正在专门查看该else
声明,并想知道这是按什么顺序发生的?我没有常规的 C 编译器,因此无法对此进行测试。当我们在执行*d++ |= (b & 0x0F);
时,这是按什么顺序发生的?
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:
b
is bitwise-AND:ed with the constant 0x0f
d
points at.d
is incremented to point at the next value.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++;
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.
++
之前会发生|=
。赋值运算符位于优先级图表的底部。
++
is done first. However post-increment (i.e. d++
here) is equivalent to this (temp=d, d++, temp)
.
根据http://www.cppreference.com/wiki/operator_precedence
它将评估 (b & 0x0F) 然后对其应用 |= 并将其分配给 *b,最后增加 *b 指向的值。
表达式*d++ |= (b & 0x0F)
分解如下:
*d++
和b & 0x0F
每个都被计算一次(没有指定它们被计算的顺序;编译器可以自由地b & 0x0F
在之前计算,*d++
因为结果不依赖于计算发生的顺序);(b & 0x0F)
位或运算。*d++
d
会更新。表达式*d++
被解析为*(d++)
; 即您正在取消引用表达式的结果d++
。表达式d++
计算为 的当前值,并且在下一个序列点之前的d
某个未指定d
点(在本例中为语句的结尾),更新 的值。更新的副作用d
不必立即应用;它可以在分配之前或之后发生。