Can a macro be used for read-only access to a variable?
-
02-07-2019 - |
Question
Can you define a macro that accesses a normal variable, but in a read-only fashion (other than defining it as a call to a function)? For example, can the VALUE macro in the following code be defined in such a way that the dostuff() function causes a compile error?
struct myobj {
int value;
}
/* This macro does not satisfy the read-only requirement */
#define VALUE(o) (o)->value
/* This macro uses a function, unfortunately */
int getvalue(struct myobj *o) { return o->value; }
#define VALUE(o) getvalue(o)
void dostuff(struct myobj *foo) {
printf("The value of foo is %d.\n", VALUE(foo)); /* OK */
VALUE(foo) = 1; /* We want a compile error here */
foo->value = 1; /* This is ok. */
}
Solution
If the variable is always numeric, this works:
#define VALUE(x) (x+0)
or in the context of your example,
#define VALUE(x) (x->value+0)
OTHER TIPS
Ok, I came up with one:
#define VALUE(o) (1 ? (o)->value : 0)
See §6.5.17 in the C standard (C99 & C1x): “A comma operator does not yield an lvalue.”
#define VALUE(x) (0, x)
(Not portable to C++.)
Try
#define VALUE(o) (const int)((o)->value)
Is this a puzzle or is it an engineering task? If it's an engineering task, then there are better ways to get opacity of structures in C. In this blog article, I wrote a decent enough description of how to do that in C.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow