course.wilkes.edu/CS125Labs
Welcome to the site for CS 125 labs!

 

Experiment 12: Assignment Associativity

Because the assignment symbol (=) is an actual operator that produces a value, the sequence of symbols

   Variable = Expression
is itself an expression that can appear to the right of an assignment operator. That is, a statement with the form
   w = x = y = z;
is a valid statements, and uses a technique sometimes called assignment chaining.

The question is, what happens when execution reaches this statement?

The answer depends on the associativity of the assignment operator. That is, if = is left associative, then the expression is evaluated as

   (((w = x) = y) = z)
but if assignment is right associative, then the expression is evaluated as
        (w = (x = (y = z)))
We can determine the answer with an experiment. If we initialize w, x, y and z to different values (say, 1, 2, 4 and 8), perform this assignment, and then display their values, the values that appear should provide us with enough information to determine whether assignment is left or right associative.

That is, suppose that w is 1, x is 2, y is 4, and z is 8. If = is left-associative, then when

   w = x = y = z;
is executed, the actions will occur in this order:
  1. w will be assigned the value of x (2);
  2. x will be assigned the value of y (4); and
  3. y will be assigned the value of z (8).
so that 2, 4, 8 and 8 will appear when the variable's values are displayed.

On the other hand, if = is right-associative, then when

   w = x = y = z;
is executed, the actions will occur in this order:
  1. y will be assigned the value of z (8);
  2. x will be assigned the value of y (8); and
  3. w will be assigned the value of x (8).
so that 8, 8, 8 and 8 will be displayed.

Modify express.cpp as necessary to conduct this experiment and record your observations and conclusions in the space below:





You should now understand more fully how the assignment operator works, and the direction in which it associates.

 
  Home

Help

Lab 0

Lab 1

Lab 2

Lab 3a

Lab 3b

Lab 4

Lab 5

Lab 6

Lab 7

Lab 8

Lab 9

Lab 10

Lab 11

Lab 12

Lab 13



Membership

Login




Last update: Tuesday, August 22, 2000 at 12:42:51 PM.
visitors to this page.