-2

Please consider the following code:

#include <iostream>

using std::cin;
using std::cout;
using std::endl;

int main() {
    int a, b;
    cout << "Enter two integer: ";
    cin >> a >> b;

    if (a > b) {
        int temp = a;
        a = b;
        b = temp;
    }
    cout << a << "<=" << b << endl;
}

The above code yields the minimum of the two inserted numbers. Can anyone explain how the if block works?

Simon
  • 1,616
  • 2
  • 17
  • 39
developer
  • 283
  • 2
  • 8
  • I generally don't get the a=b and b=temp. What do these two lines do? – developer Nov 05 '19 at 14:11
  • Have you ever carried a heavy thing in each hand and you exchange the things in your hands by temporarily putting down just one of them so you can change hand for the other heavy thing without putting it down, and then you pick up the first thing again? It's exactly that. – molbdnilo Nov 05 '19 at 14:47
  • @molbdnilo: Does XOR swap correspond to juggling? – Bathsheba Nov 05 '19 at 14:49
  • For learning C++, you'll find one of these [good books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) to be very helpful. – Eljay Nov 05 '19 at 15:07
  • In general, you'd probably want to use [std::swap](https://en.cppreference.com/w/cpp/algorithm/swap) instead.. – Jesper Juhl Nov 05 '19 at 17:24

1 Answers1

6

It's the idiomatic way of swapping two numbers.

There are more efficient ways: to exploit those use std::swap instead.

(The statement int temp=a; sets the variable temp to the value of a. The statement a=b; sets a to the value of b. Finally, b=temp; sets b to temp which was the original value of a. The overall effect therefore is to exchange the values of a and b.)

Bathsheba
  • 231,907
  • 34
  • 361
  • 483