你能定义一个访问普通变量的宏,但是只能以只读方式(除了将其定义为对函数的调用)吗?例如,以下代码中的VALUE宏是否可以通过dostuff()函数导致编译错误的方式定义?

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) (1 ? (o)->value : 0)

参见C标准中的§ 6.5.17(C99& C1x):“逗号运算符不会产生左值。”

#define VALUE(x) (0, x)

(不能移植到C ++。)

尝试

#define VALUE(o) (const int)((o)->value)

这是一个难题还是一项工程任务? 如果这是一项工程任务,那么有更好的方法可以在C中获得结构的不透明度。在这篇博客文章,我写了一篇关于如何在C中做到这一点的足够好的描述。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top