Section 1.29 Worked Example: Swap
Subgoals for evaluating an assignment statement.
- Determine resultant data type of expression
- Update variable for pre-increment or pre-decrement operators (side effect)
- Evaluate arithmetic expression according to operator precedence
- If an assignment statement (=), is Left Hand Side (LHS) a variable? Check data type of value against data type of variable.
- 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.
You have attempted of activities on this page.