-2

we usually use the

a=a+b; 
b=a-b; 
a=a-b;

logic to solve this code, however, if we work with int, then after say 30000 the code fails, if we take long, it fails after say 1000000 or so. My objective is, not to increase the length of the code yet, do the same operation. I have already tried using a BIT wise XOR,

a = a ^ b;
b = a ^ b;
a = a ^ b;

Still it didn't help, any ideas?

user703016
  • 37,307
  • 8
  • 87
  • 112
Ankit Aich
  • 25
  • 5

1 Answers1

5

To swap a variable a and a variable b: std::swap(a, b);
Example:

int a = 10;
int b = 20;

std::cout << "Before swap\n";
std::cout << "Value of a: " << a << '\n';
std::cout << "Value of b: " << b << '\n';

std::swap(a, b);

std::cout << "After swap\n";
std::cout << "Value of a: " << a << '\n';
std::cout << "Value of b: " << b << '\n';

Output using GCC 4.9.2:

Before swap
Value of a: 10
Value of b: 20
After swap
Value of a: 20
Value of b: 10

This way of doing it uses rvalues internally, so it has next to zero overhead for other use cases and won't overflow for any primitive type ever

Jan Hohenheim
  • 3,552
  • 2
  • 17
  • 42
  • Moving an int has exactly the same cost as copying it. And no, std::swap specifically doesn't work with r-values (it uses them internally, but again, for int that doesn't make a difference). – MikeMB Sep 30 '16 at 07:05
  • @MikeMB good point about using rvalues only internally, I thought it would be clear in the context. Edited to bo explicit. And yes, it's the same for ints, but I try to answer questions as broadly applicable as possible, so I wanted to point out the general benefits of `std::swap` – Jan Hohenheim Sep 30 '16 at 07:07
  • Its also the question, if the answer to: "I don't want to use a third variable" is to create 1 (effectively 3) new variables in a function and call that function. – MikeMB Sep 30 '16 at 07:07
  • 1
    @PatrickM'Bongo I'm sorry if my choice of words is confusing. What I'm trying to convey is that there's a possible runtime cost associated with operations such as `a-b;`, which is not present using `b = std::move(a)` internally. Also yes, in this specific example the temp variable that is probably created (not guaranteed to, though) uses a regular copy. The real benefit starts kicking in as soon as the OP uses `std::swap` for non-primitive data types like `std::vector` , which will not generate copying overhead. – Jan Hohenheim Sep 30 '16 at 07:19