C-交换两个变量的值

1 int 类型

void SwapInt(int *a, int *b) {
  int temp = *a;
  *a = *b;
  *b = temp;
}

2 通用类型

void Swap(void *first, void *second, size_t size) {
  void *temp = malloc(size);
  if (temp) {
    memcpy(temp, first, size);
    memcpy(first, second, size);
    memcpy(second, temp, size);

    free(temp);
  } else {
    // ...
  }
}

3 宏

// msvc C++ decltype(a)
#define SWAP(a, b, type) do { type temp = a; a = b; b = temp; }while (0)
#define SWAP_EXT(a, b) do { typeof(a) temp = a; a = b; b = temp; }while (0)