Hygienic Macros ใน C เรารู้จัก macros แต่บางครั้งไม่ให้ผลลัพธ์ที่ต้องการ เพราะ accidental capture ของ identifiers
ดูโค้ดนี้ ไม่ทำงานถูกต้อง:
ตัวอย่าง
#include<stdio.h> #define INCREMENT(i) do { int a = 0; ++i; } while(0) main(void) { int a = 10, b = 20; INCREMENT(a); INCREMENT(b); printf("a = %d, b = %d\n", a, b); }หลัง preprocess โค้ดจะกลายเป็น:
ตัวอย่าง
#include<stdio.h> #define INCREMENT(i) do { int a = 0; ++i; } while(0) main(void) { int a = 10, b = 20; do { int a = 0; ++a; } while(0); do { int a = 0; ++b; } while(0); printf("a = %d, b = %d\n", a, b); }ผลลัพธ์
a = 10, b = 21
ค่า a ไม่ได้อัปเดต ใช้ hygienic macros ซึ่งรับประกันว่า expansion ไม่ทำ accidental capture ใช้ชื่อตัวแปรที่ไม่ชนกับโค้ด เช่น 't'
ตัวอย่าง
#include<stdio.h> #define INCREMENT(i) do { int t = 0; ++i; } while(0) main(void) { int a = 10, b = 20; INCREMENT(a); INCREMENT(b); printf("a = %d, b = %d\n", a, b); }ผลลัพธ์
a = 11, b = 21