4E. Assignments Are Expressions

In C++, assignments and abbreviations for assignments are actually expressions. Expression x = E (without a semicolon) has the side effect of changing x, and its value is the value that was just stored into x.


Multiple assignment

Look at the following.

  int n = 40;
  a = b = n + 1;
Operator = has very low precedence, and two or more = operators are done from right to left. Adding parentheses to show what is going on gives:
  a = (b = n + 1);
Expression b = n + 1 stores 41 into b, and its value is 41. Next, 41 is stored into a. Using two or more = operators is called multiple assignment, and you can feel free to use it.


Standards for using assignments as expressions

The standards for this course require that you not use an assignment as an expression in any way other than multiple assignment. For example, do not use x = f(n) as an argument of a function call. (See functions.)