Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Why does this version of the swap function fail to work? Is there a fix? (Choose

ID: 3930296 • Letter: W

Question

Why does this version of the swap function fail to work? Is there a fix? (Choose 2) oid swap (int & lhs, int & rhs) Select one or more: It fails because the programmer forgot to make the parameters call-by-reference. Of course it works ! Just look at it It clearly swaps the two parameters! It fails OK, and we can fix it we can just reverse the order of the lines. To fix this, we must save the the value in a local variable before making the first assignment indicated, then instead of the second Iine, as int local = lhs; Ihs = rhs; rhs = local; It fails because the first line destroys the old value of ihs without saving it. Then both variables have the old value of rhs in them.

Explanation / Answer

Choice d, and e are valid options.

To swap the elements, we need to first copy the value of first variable to temporary variable, then copy the second variable to first variable, finally copy the value in temporary variable to second variable.

So,

int local = lhs;

lhs = rhs;

rhs = local;

is the perfect way to swap two values.

The last option is the actual problem with the given code.

When we do lhs = rhs, the old value of lhs is destroyed, and now, both lhs and rhs are holding the same value, that is the value in rhs. And then, the second operation rhs = lhs, is of no use, as both of them are holding the same value.

Therefore, options d, and e are correct.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote