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 operators based on side effect
  3. Solve arithmetic equation, operator precedence
  4. If = statement, is Left Hand Side (LHS) a variable? Check data type of copied value against data type of variable
  5. Update variable for post operators based on side effect

Subsection 1.29.1

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.