宏可以用于对变量的只读访问吗?
时间:2020-03-06 14:47:46 来源:igfitidea点击:
我们是否可以定义一个以只读方式访问普通变量的宏(而不是将其定义为对函数的调用)?例如,是否可以以dostuff()函数导致编译错误的方式定义以下代码中的VALUE宏?
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. */
}
解决方案
如果变量始终是数字,则可以这样做:
#define VALUE(x) (x+0)
或者在示例中,
#define VALUE(x) (x->value+0)
尝试
#define VALUE(o) (const int)((o)->value)
好吧,我想出了一个:
#define VALUE(o) (1 ? (o)->value : 0)
这是难题还是工程任务?
如果这是一项工程任务,那么有更好的方法可以使C语言中的结构变得不透明。在这篇博客文章中,我对如何在C语言中实现这一点做了足够不错的描述。

