void DoesSomething(int *first, int *second) {
*first = *second - *first;
*second = *second - *first;
*first = *second + *first;
}
利用加減法實現無臨時變量交換:
1. *first = b - a
2. *second = b - (b - a) = a
3. *first = a + (b - a) = b
最終 *first=b, *second=a。**功能等價於交換兩數值。**
INT_MAX) 導致未定義行為。
void DoesSomething(int *first, int *second) {
int tmp = *first;
*first = *second;
*second = tmp;
}
#include
void DoesSomething(int &first, int &second) {
std::swap(first, second); // 類型安全、支持移動語義、可優化
}