getting error: cannot take the address of an rvalue of type 'int'

getting error: cannot take the address of an rvalue of type 'int'

我尝试用新编译器编译旧代码,但出现下一个错误:

error: cannot take the address of an rvalue of type 'int'

这是包含 2 行的示例 - 一行编译,另一行给出错误

struct mstct {
    int myfield;
    int myfield2[5];
    int myfield3[5];
};

typedef struct mstct db_data_px;

int foo(int a, int b, int c){

  //the next code compiles successfully.
  unsigned val1 = ((18 == c) ? ((unsigned) & (((db_data_px *) 0)->myfield)) : ((unsigned) & (((db_data_px *) 0)->myfield3[b]))); //successes


  //the next code is failing
  unsigned val2 = (unsigned) & ((18 == c) ? (((db_data_px *) 0)->myfield) : (((db_data_px *) 0)->myfield3[b]));
  return 0; // failing
}

为什么第一行编译成功而第二行失败?为什么我需要在两个 select 表达式中都强制转换 (unsigned) & 而仅在 select 表达式被赋值后才强制转换是不够的?

在你的代码中

   ((18 == c) ? (((db_data_px *) 0)->myfield) : (((db_data_px *) 0)->myfield3[b]))

是一个不产生左值的条件表达式。

上面的表达式给你一个右值 (non-lvaue),你不能在上面使用 & 运算符。

详细说明,引用 C11 标准,章节 §6.5.3.2,地址和间接运算符

The operand of the unary & operator shall be either a function designator, the result of a [] or unary * operator, or an lvalue that designates an object that is not a bit-field and is not declared with the register storage-class specifier.

OTOH,对于条件运算符的结果类型,章节 §6.5.15,脚注

A conditional expression does not yield an lvalue.

试想一下,&5,不可能。