Why does this version of the swap function fail to work Is t

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.

Solution

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.

 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 becaus

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site