2

你能定义一个访问普通变量的宏,但是以只读方式(除了将其定义为对函数的调用)吗?例如,以下代码中的 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. */
}
4

5 回答 5

11

好的,我想出了一个:

#define VALUE(o) (1 ? (o)->value : 0)
于 2008-09-26T17:44:05.523 回答
7

如果变量总是数字,这有效:

#define VALUE(x) (x+0)

或在您的示例中,

#define VALUE(x) (x->value+0)
于 2008-09-26T17:37:44.820 回答
6

请参阅 C 标准(C99 和 C1x)中的第 6.5.17 节:“逗号运算符不会产生左值。”</p>

#define VALUE(x) (0, x)

(不能移植到 C++。)

于 2011-01-31T18:47:25.747 回答
2

尝试

#define VALUE(o) (const int)((o)->value)
于 2008-09-26T17:39:43.707 回答
-1

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

于 2008-09-26T17:54:38.977 回答