您是否可以定义一个以只读方式访问普通变量的宏(而不是将其定义为对函数的调用)?例如,是否可以以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)

关于c - 宏可以用于对变量的只读访问吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/140825/

10-12 16:06
查看更多