宏可以用于对变量的只读访问吗?

Jos*_*ink 2 c c-preprocessor

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

  • 实际上可能没有,我认为结肠两侧的数据类型在第三级运算符中必须相同.因此,如果o-> value是一个结构,例如,我认为这不会起作用.你可以把(o) - >值放在冒号的两边. (3认同)

Mar*_*som 7

如果变量始终是数字,则可以:

#define VALUE(x) (x+0)
Run Code Online (Sandbox Code Playgroud)

或者在你的例子中,

#define VALUE(x) (x->value+0)
Run Code Online (Sandbox Code Playgroud)


J. *_*mon 6

参见C标准(C99和C1x)中的§6.5.17:"逗号运算符不会产生左值."

#define VALUE(x) (0, x)
Run Code Online (Sandbox Code Playgroud)

(不能移植到C++.)