Skip to main content

Section 1.29 Worked Example: Swap

Subgoals for evaluating an assignment statement.

  1. Determine resultant data type of expression
  2. Update variable for pre-increment or pre-decrement operators (side effect)
  3. Evaluate arithmetic expression according to operator precedence
  4. If an assignment statement (=), is Left Hand Side (LHS) a variable? Check data type of value against data type of variable.
  5. Update variable for post-increment or post-decrement operators (side effect)
You can watch this video or read through the content below it.
Consider these declarations.
int x,y,z;
x = 7;
y = 13;
Now consider this code for swapping the values of x and y. Note the need for a third variable to hold the value of x so that it is not lost when assigning the value of y into x.
z = x;
x = y;
y = z;
The diagram below shows the changes in memory after executing each of the six lines of code.
Figure 1.29.1.

Practice Pages.

You have attempted of activities on this page.