#define SWAP(x, y, T) do { T temp##x##y = x; x = y; y = temp##x##y; } while (0)
我看到這個交換宏C.在下面的語句中,##運算符有什麼用處?
有人能解釋一下它的工作原理和使用temp##x##y
?
#define SWAP(x, y, T) do { T temp##x##y = x; x = y; y = temp##x##y; } while (0)
我看到這個交換宏C.在下面的語句中,##運算符有什麼用處?
有人能解釋一下它的工作原理和使用temp##x##y
?
它連接temp
與x
和y
來幫助聲明T
類型的變量,這將允許交換工作。
您可以使用它像這樣
int a = 1;
int b = 2;
SWAP(a, b, int);
生成的代碼將
int a = 1;
int b = 2;
do {
int tempab = a;
a = b;
b = tempab;
} while (0);
它避免了使用相同的名稱所傳遞的變量,你可以看到,因爲假設你定義的宏像這樣
#define SWAP(x, y, T) do { T z = x; x = y; y = z; } while (0)
那麼這個
int x = 1;
int z = 2;
SWAP(z, x, int);
將不起作用。
[令牌串聯](https://gcc.gnu.org/onlinedocs/cpp/Concatenation.html)... – 2015-03-13 18:39:14