An assignment statement assigns a value to a storage location. For example, the following statement assigns the integer 25
to the location represented by the variable carrots
:
carrots = 25;
The =
symbol is called the assignment operator. One unusual feature of C++ (and C) is that you can use the assignment operator serially. For example, the following is valid code:
int steinway;
int baldwin;
int yamaha;
yamaha = baldwin = steinway = 88;
The assignment works from right to left. First, 88
is assigned to steinway
; then the value of steinway
, which is now 88, is assigned to baldwin
; then baldwin
’s value of 88 is assigned to yamaha
. (C++ follows C’s penchant for allowing weird-appearing code.)
The second assignment statement in Listing 2.2 demonstrates that you can change the value of a variable:
carrots = carrots - 1; // modify the variable
The expression to the right of the assignment operator (carrots – 1
) is an example of an arithmetic expression. The computer will subtract 1 from 25, the value of carrots
, obtaining 24. The assignment operator then stores this new value in the carrots
location.
18.119.103.204