我们都很熟悉 宏 在像C这样的语言中,由于意外捕获标识符,宏扩展可能会导致不希望的结果。 例如:
null
// C program to illustrate a situation known as // accidental capture of identifiers - an // undesirable result caused by unhygienic macros #define INCI(i) do { int x = 0; ++i; } while(0) int main( void ) { int x = 4, y = 8; // macro called first time INCI(x); // macro called second time INCI(y); printf ( "x = %d, b = %d" , x, y); return 0; } |
该代码实际上相当于:
// C program to illustrate unhygenic macros // with Macro definition substituted in source code. int main( void ) { int x = 4, y = 8; //macro called first time do { int x = 0; ++x; } while (0); //macro called second time do { int x = 0; ++y; } while (0); printf ( "x = %d, b = %d" , x, y); return 0; } |
输出:
x = 4, y = 9
在主函数范围内声明的变量a被宏定义中的变量a掩盖,因此 a=4 从不更新(称为意外捕获)。
卫生宏
卫生宏是指其扩展保证不会导致意外捕获标识符的宏。宏不会使用可能会干扰正在扩展的代码的变量名。 只需更改宏定义中变量的名称即可避免上述代码中的情况,这将产生不同的输出。
// C program to illustrate // Hygienic macros using // identifier names such that // they do not cause // the accidental capture of identifiers #define INCI(i) do { int m = 0; ++i; } while(0) int main( void ) { int x = 4, y = 8; // macro called first time INCI(x); // macro called second time INCI(y); printf ( "x = %d, y = %d" , x, y); return 0; } |
输出:
x = 5, y = 9
本文由 帕拉什尼甘酒店 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。
如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END