Madiyar's blog

By Madiyar, history, 9 years ago, In English

Small brainteaser. Do you know that function below doesn't work in some cases.
Try to attack it.

#include <iostream>

using namespace std;

void swap(int &a, int &b){ 
	a = a + b; 
	b = a - b; 
	a = a - b;
}
  • Vote: I like it
  • +55
  • Vote: I do not like it

| Write comment?
»
9 years ago, # |
Rev. 2   Vote: I like it +42 Vote: I do not like it

attempt in edit.

  • »
    »
    9 years ago, # ^ |
      Vote: I like it +37 Vote: I do not like it

    Yeap, it is true. But more interesting example is swap(a[i], a[j]), and accidentally i == j.

»
9 years ago, # |
  Vote: I like it +37 Vote: I do not like it

do you mean the overflow, when a + b > 2^31 — 1

»
9 years ago, # |
Rev. 2   Vote: I like it +16 Vote: I do not like it

do not work if *a == *b

even it occurs overflow, it works well

  • »
    »
    9 years ago, # ^ |
      Vote: I like it +13 Vote: I do not like it

    it is UB in case of overflow signed integers

»
9 years ago, # |
  Vote: I like it +23 Vote: I do not like it

int a=12; swap(a,a);

»
9 years ago, # |
Rev. 13   Vote: I like it +1 Vote: I do not like it

best swap function without overflows :)

void swap (int &a, int &b){ 
  if (&a != &b ) { 
	a ^= b; 
	b ^= a; 
	a ^= b;
      }
}
why downvotes ? :D epic 
  • »
    »
    9 years ago, # ^ |
      Vote: I like it -26 Vote: I do not like it

    Does not work if value of a is equal to value of b. In this case after XOR operation a and b will be equal to zero.

»
9 years ago, # |
  Vote: I like it +11 Vote: I do not like it

that's why Mozilla created Rust. In this language any attempt to call swap(a, a) will lead to compile-time error. Prooflink: http://is.gd/m65CVw