你能定义一个访问普通变量的宏,但是只能以只读的方式定义(除了将它定义为对函数的调用)吗?例如,以下代码中的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. */
}
Run Code Online (Sandbox Code Playgroud)
Jos*_*ink 11
好的,我提出了一个:
#define VALUE(o) (1 ? (o)->value : 0)
Run Code Online (Sandbox Code Playgroud)
如果变量始终是数字,则可以:
#define VALUE(x) (x+0)
Run Code Online (Sandbox Code Playgroud)
或者在你的例子中,
#define VALUE(x) (x->value+0)
Run Code Online (Sandbox Code Playgroud)
参见C标准(C99和C1x)中的§6.5.17:"逗号运算符不会产生左值."
#define VALUE(x) (0, x)
Run Code Online (Sandbox Code Playgroud)
(不能移植到C++.)