-3

So I need to switch between A and B without using another integer.

I was able to do this easily with a third integer (tmp). Is there any way to do this without it?

int a = 53, b = 12, tmp = 0;
tmp = a;
a = b;
b = tmp;
EV3
  • 39
  • 5
  • 4
    That is the proper way. Any other way may make the compiler miss an optimization, for example. – pmg Nov 08 '19 at 08:50
  • 1
    A better question is: is there ever a reason to switch between A and B without using another integer? I'd start with that one. – Lundin Nov 08 '19 at 09:05
  • There is so many bundle of ways to do this: please refer all solutions, and its usage..[https://www.geeksforgeeks.org/c-program-swap-two-numbers/] – VJAYSLN Nov 08 '19 at 09:39

3 Answers3

3

The most common mentioned method is:

y ^= x;
x ^= y;
y ^= x;

An alternative is to use addition and subtraction instead of XOR; but that's messy due to the risk of overflows.

Note: To be precise; XOR causes undefined behavior for negative values (but that can be prevented with simple casts to unsigned and back to signed); and addition/subtraction can cause overflow which is also undefined behavior, but there's no easy fix for that.

Of course no sane person would ever do this in real code (it's faster and cheaper to use a temporary variable).

Brendan
  • 35,656
  • 2
  • 39
  • 66
  • "XOR causes undefined behavior for negative values" Setting the sign bit with bitwise operators isn't necessarily undefined behavior. It is well-defined in case of `| & ^ ~` but undefined in case of `<<` and impl. defined in case of `>>`. – Lundin Nov 08 '19 at 09:04
  • I'd add a warning that if `x` and `y` alias, this is not a no-op but set the. common, value to 0. – AProgrammer Nov 08 '19 at 09:10
0

Yes, there is an other way to do it:

int a=53, b=12;
a = a + b; // a = 65
b = a - b; // b = 53
a = a - b; // a = 12
pmg
  • 106,608
  • 13
  • 126
  • 198
Phantom
  • 833
  • 1
  • 9
  • 26
0

You can do that using arithmetic addition and subtraction between those two variables.

int a = 53, b = 12;
a = a + b;
b = a - b;
a = a - b;
pmg
  • 106,608
  • 13
  • 126
  • 198
Roy
  • 1,189
  • 7
  • 13