[英]Why assignment operator = doesn't return the value of pointer but the dereference value?
From What does an assignment return?从任务返回什么? :
:
An assignment expression has the value of the left operand after the assignment
赋值表达式在赋值后具有左操作数的值
and this code:这个代码:
#include <iostream>
using namespace std;
int main() {
int a[5] = { 0,1,2 };
int* a_ptr = a;
int b = (*a_ptr++ = 3); //int *b won't compile
cout << b << endl; //3
}
What is the left operand of =
when evaluating (*a_ptr++ = 3)
?求值
(*a_ptr++ = 3)
时=
的左操作数是什么?
What's the definition of an operand ?操作数的定义是什么? In my mind, an operand is an identifier or name which is
aptr
.在我看来,操作数是
aptr
的标识符或名称。
int b = (*a_ptr++ = 3);
is grouped as int b = (*(a_ptr++) = 3);
被分组为
int b = (*(a_ptr++) = 3);
. . Note that the parentheses are superfluous;
注意括号是多余的; you could have written
你可以写
int b = *a_ptr++ = 3;
which in many ways makes the result more obvious, since the right-to-left associativity of =
is such that the 3 carries over to the value of b
.这在许多方面使结果更加明显,因为
=
的从右到左的结合性使得 3 延续到b
的值。
a_ptr++
is an expression equal to a_ptr
but it will point to the second element of the array a
once the whole statement completes. a_ptr++
是一个等于a_ptr
的表达式,但一旦整个语句完成,它将指向数组a
的第二个元素。 Since you don't make use of that incremented pointer, the ++
is a red-herring, so the statement simplifies to由于您不使用该递增指针,因此
++
是一个红鲱鱼,因此该语句简化为
int b = *a_ptr = 3;
whereupon it's clear that *a_ptr = 3
has the effect of setting the first element of the array a
to 3 and is an expression equal to 3, which is assigned to b
.因此很明显
*a_ptr = 3
具有将数组a
的第一个元素设置为 3 的效果,并且是一个等于 3 的表达式,它被分配给b
。
The left operand is *a_ptr++
.左操作数是
*a_ptr++
。 As per the operator precedence , it's evaluated as根据 运算符优先级,它被评估为
*(a_ptr++)
where the post-increment is sequenced as a side effect, after the execution of the statement.在执行语句之后,后增量作为副作用进行排序。 The value of the operand is the result of the statement.
操作数的值是语句的结果。 So, it's equivalent to
所以,它相当于
int b = (*a_ptr = 3);
a_ptr++;
That said, in general, Operands are expressions or values on which an operator operates or works.也就是说,一般来说,操作数是运算符对其进行操作或工作的表达式或值。 So, it can be
所以,可以
var
, as in int var
)var
,如int var
)5
or '"Hello"')5
或 '"Hello"')*a_ptr++
)*a_ptr++
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.