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. */ }
If the variable is always numeric, this works:
or in the context of your example,