yeh*_*ahs 8 c gcc ternary-operator conditional-operator addressof
我尝试使用新编译器编译旧代码并得到下一个错误:
error: cannot take the address of an rvalue of type 'int'
Run Code Online (Sandbox Code Playgroud)
下面是两行示例 - 一行编译,另一行编译错误
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
}
Run Code Online (Sandbox Code Playgroud)
为什么第一行编译而第二行失败?为什么我需要在select表达式中强制转换(unsigned)&仅仅在select表达式被赋值后才能进行转换?
在你的代码中
((18 == c) ? (((db_data_px *) 0)->myfield) : (((db_data_px *) 0)->myfield3[b]))
Run Code Online (Sandbox Code Playgroud)
是一个不产生左值的条件表达式.
上面的表达式给你一个rvalue(非lvaue),你不能使用&运算符.
详细说明,引用C11标准,章节§6.5.3.2,地址和间接运算符
一元运算
&符的操作数应该是函数指示符,[]一元或一元运算*符的结果 ,或者是一个左值,它指定一个不是位字段且不用register存储类说明符声明的对象.
OTOH,对于条件运算符的结果类型,章节§6.5.15,脚注
条件表达式不会产生左值.
想象一下,&5不可能.
| 归档时间: |
|
| 查看次数: |
13299 次 |
| 最近记录: |