如果我有一个全局变量" x"由C函数使用
int foo() {
extern int x;
return x;
}
我可以禁止foo修改x吗?即以与下面的替代方案相同的方式处理x?
int foo(const int x) {
return x;
}
答案 0 :(得分:1)
#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的const要求是否违反,它们可能会很有用。