+ 1
How we can inter change the value of two variables with or without 3 rd variables?
2 Réponses
+ 3
With a third variable:
void swap(int &a, int &b) {
int tmp = a;
a = b;
b = tmp;
}
Without:
void swap(int &a, int &b) {
a = a + b;
b = a - b;
a = a - b;
}
Call:
int a = 31;
int b = 42;
swap(a, b);
+ 1
You will always need a third variable to hold one of the other variable's values before you overwrite it. This is the same with pointers as well. You can make a function to swap to variables' values:
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;//even in the function, you need that third variable.
}
call it like this:
int aa = 6;
int bb = 9;
swap(&aa, &bb);