简体   繁体   中英

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) ?

What's the definition of an operand ? In my mind, an operand is an identifier or name which is aptr .

int b = (*a_ptr++ = 3); is grouped as 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 .

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. 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 .

The left operand is *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

  • a variable (ex: var , as in int var )
  • a literal ( 5 or '"Hello"')
  • an expression (like *a_ptr++ )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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