如果我有c函数使用的全局变量" x"
int foo() {
extern int x;
return x;
}
我可以禁止foo修改x吗?IE。以下面的替代方案对待x?
int foo(const int x) {
return x;
}
方法一:const copy
#define HorribleHackStart(Type, Name)
Type HorribleHackTemp = Name; { const Type Name = HorribleHackTemp;
#define HorribleHackEnd
}
int foo(void)
{
HorribleHackStart(int, x)
... Here x is an unchanging const copy of extern x.
... Changes made to x (by other code) will not ge visible.
HorribleHackEnd
}
方法两个:指针
int foo(void)
{
#define x (* (const int *) &x)
... Here x is effectively a const reference to extern x.
... Changes made to x (by other code) will be visible.
#undef x
}
评论
我不会在生产代码中使用其中任何一个,但是如果您想编译代码以测试函数内X内X的const要求的行为,则它们可能很有用。