Reputation: 699
If I have a global variable "x" used by a C function
int foo() {
extern int x;
return x;
}
Can I forbid foo from modifying x? I.e. treat x the same way the alternative below would?
int foo(const int x) {
return x;
}
Upvotes: 0
Views: 59
Reputation: 223795
#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
}
I would not use either of these in production code, but they might be useful if you wanted to compile the code to test for violations of the const requirement for x inside the function.
Upvotes: 1