-5

if I have 2 variables to set equal to each other how would I go about that? for example, if I had 2 numbers (3 , 8) so xval = 3 and yval = 8 how would I swap them with the following procedure?

xval = yval;
yval = xval;

this would just set both values to y which would output (8 , 8). I remember earlier in my lass there was a function to store a value for later use but I forgot what it was

  • 4
    Declare a third temporary variable, or better use `std::swap`. – Nate Eldredge Oct 26 '21 at 03:46
  • And a more exotic one if you are dealing with integers, you can use XOR operations, no third variable needed. E.g., swap value of `a` with `b`: `a^= b; b^=a; a^=b`. The fundamental behind that is that `x^x==0` – Zois Tasoulas Oct 26 '21 at 03:50
  • https://stackoverflow.com/a/3933432/9248466 – Ghasem Ramezani Oct 26 '21 at 03:52
  • 3
    @zois The XOR swap, on modern architectures, is usually slower than a swap that involves a temporary variable and also (if it is to work) inhibits some optimisations related to instruction pipelining (if those optimisations are not inhibited, the swap isn't guaranteed to actually work). It also doesn't work if `a` and `b` overlap in memory (e.g. one is an alias of the other, directly or indirectly). – Peter Oct 26 '21 at 05:03

1 Answers1

-1

1. Using pre-defined swap

std::swap(xval , yval);

2. Using temporary variable

int temp=xval;
xval = yval;
yval = temp;

3. Without using the temporary variable (Watch for overflow)

xval = xval+yval;
yval = xval-yval;
xval = xval-yval;

4. Using XOR

xval = xval ^ yval ^ (yval = xval);
Saurabh Dhage
  • 1,478
  • 5
  • 17
  • 31