Skip to content

Instantly share code, notes, and snippets.

@MitMaro
Created September 10, 2012 15:19
Show Gist options
  • Save MitMaro/3691466 to your computer and use it in GitHub Desktop.
Save MitMaro/3691466 to your computer and use it in GitHub Desktop.
Why you need symbol concat in macro
/* If you had this it would break */
#define SWAP(x, y, T) do { T temp = x; x = y; y = temp; } while (0)
int main(void) {
int temp;
int a = 1;
int b = 2;
SWAP(a, b, int);
}
/* Would be: */
int main(void) {
int temp = 3;
int a = 1;
int b = 2;
do { int temp = x; x = y; y = temp; } while (0);
}
/* Which would override the temp value */
/* If you had this it would break */
#define SWAP(x, y, T) do { T temp = x; x = y; y = temp; } while (0)
int main(void) {
int temp;
int a = 1;
int b = 2;
SWAP(a, b, int);
}
/* Would be: */
int main(void) {
int temp = 3;
int a = 1;
int b = 2;
do { int temp = x; x = y; y = temp; } while (0);
}
/* Which would override the temp value */
/* If you had this it would break */
#define SWAP(x, y, T) do { T temp = x; x = y; y = temp; } while (0)
int main(void) {
int temp;
int a = 1;
int b = 2;
SWAP(a, b, int);
}
/* Would be: */
int main(void) {
int temp = 3;
int a = 1;
int b = 2;
do { int temp = x; x = y; y = temp; } while (0);
}
/* Which would override the temp value */
/* If you had this it would break */
#define SWAP(x, y, T) do { T temp = x; x = y; y = temp; } while (0)
int main(void) {
int temp;
int a = 1;
int b = 2;
SWAP(a, b, int);
}
/* Would be: */
int main(void) {
int temp = 3;
int a = 1;
int b = 2;
do { int temp = x; x = y; y = temp; } while (0);
}
/* Which would override the temp value */
/* If you had this it would break */
#define SWAP(x, y, T) do { T temp = x; x = y; y = temp; } while (0)
int main(void) {
int temp;
int a = 1;
int b = 2;
SWAP(a, b, int);
}
/* Would be: */
int main(void) {
int temp = 3;
int a = 1;
int b = 2;
do { int temp = x; x = y; y = temp; } while (0);
}
/* Which would override the temp value */
/* If you have this it would not break */
#define SWAP(x, y, T) do { T temp##x##y = x; x = y; y = temp##x##y; } while (0)
int main(void) {
int temp;
int a = 1;
int b = 2;
SWAP(a, b, int);
}
/* Would be: */
int main(void) {
int temp = 3;
int a = 1;
int b = 2;
do { int temp12 = x; x = y; y = temp12; } while (0);
}
/* Which is ok */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment