3

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.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
Rick
  • 7,007
  • 2
  • 49
  • 79
  • 2
    An operand is whatever "argument" you give to the operator. Does not have to be an identifier or name - `3` is neither, but still you used it as an operand without issue. – Mat Dec 29 '20 at 12:28
  • 1
    Why did you tag this with C? This is C++ code. – Andrew Henle Dec 29 '20 at 12:29

2 Answers2

3

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.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • Would be better to mention operator precedence as well. – Jarvis Dec 29 '20 at 12:32
  • @Jarvis: Operator precedence drops out of the language grammer. It's not therefore a fundamental concept. I prefer to talk in terms of groupings. That said, feel free to put in an answer of your own. – Bathsheba Dec 29 '20 at 12:37
1

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++)
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261