简体   繁体   English

C ++运算符优先级=,*和++

[英]C++ Operator priority =, * and ++

I have a question with this pointer value assignment: 我对此指针值分配有疑问:

*p++ = *q++;

According to Operator Priority Table 根据运营商优先级表

The priorities of operators are "++" > "*" > "=". 运算符的优先级为“ ++”>“ *”>“ =”。

But the result of the above statement does the assignment "=" first, as the following 但是,上面语句的结果首先执行赋值“ =”,如下所示

*p = *q;
p++;
q++; 

Why? 为什么?

The post-increment operator increments its operand after its value has already been computed. 在计算其值之后 ,后递增运算符将其操作数递增 The pointer dereference therefore occurs on the values the pointers held before this line. 因此,指针取消引用发生在该行之前保持的指针的值上。 However, the precedence you give is correct; 但是,您给出的优先级是正确的。 the expression is indeed equivalent to 该表达确实等于

(*(p++)) = (*(q++))

因为它们是修复后的运算符,而不是修复前的运算符!

You're missing an important distinction. 您缺少重要的区别。 An operator has a value, and it may have side effects. 运算符具有值,并且可能会有副作用。 In the case of postfix ++ , the value is the value before the incrementation, and the side effect is thhe incrementation. 在postfix ++的情况下,该值为增量之前的值,而副作用为增量。 What is used in the expression is the value. 表达式中使用的是值。 The side effects may occur at any time before the end of the full expression (in pre-C++11 terms, but the actual effect hasn't changed); 副作用可能在完整表达式结束之前的任何时间发生(以C ++ 11之前的术语,但实际效果没有改变); a compiler might start by incrementing the two pointers, saving their previous values in registers and using them in the rest of the expression, or by using the values directly from memory, and deferring the incrementation of both pointers until the end of the expression. 编译器可能首先增加两个指针,将其先前的值保存在寄存器中,然后在表达式的其余部分中使用它们,或者直接使用内存中的值,然后将两个指针的增量推迟到表达式的末尾。 Or any combination of operations which results in the same observable behavior. 或导致相同可观察行为的任何操作组合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM