c - 获取条件表达式的地址
问题描述
我有以下代码:
struct S {
int x;
};
#define X(a, s) ((struct S*)(a ? &s : 0))
int main(void)
{
int a;
struct S s;
struct S *t;
int *x;
a = 3;
s.x = 4;
x = &(X(a, s)->x);
t = &(X(a, s));
}
当我编译这个时,我在最后一行得到一个错误:
test.c: In function ‘main’:
test.c:18:9: error: lvalue required as unary ‘&’ operand
t = &(X(a, s));
^
为什么 "&(X(a, s)->x)" 是有效代码,但 "&(X(a, s))" 不是?两者都涉及返回条件表达式的地址。
解决方案
在&(X(a, s))
中,&
适用于((struct S*)(a, &s : 0))
。该表达式的类型是struct S*
,它是一个值(指向 a 的指针的值struct S
)。&
可能不适用于不是左值的值。1
在&(X(a, s)->x)
中,&
适用于((struct S*)(a, &s : 0))->x
。该表达式接受一个指向 a 的指针struct S
并使用它来引用成员x
,即 a int
。它是一个左值,因为它指定了int
作为成员的对象x
(C 2018 6.5.2.3 4 明确表示结果->
是一个左值)。由于它是一个左值,&
因此可以应用于它。
脚注
1根据 C 2018 6.5.3.2 1,地址运算符&
必须应用于函数指示符、[ ]
或一元的结果或*
指定不是位域且未用 声明的对象的左值register
。
推荐阅读
- haskell - 在哪里可以找到 Stack 的 package.yaml 的对应名称列表,从 Haskell 代码中的 Import 语句中了解包名称
- python - 给定数据集的傅里叶变换和滤波
- javascript - 使用 DOM 操作传递具有应用样式的元素
- html - 如何在白色背景的图像顶部添加导航栏
- python - 为什么 Pandas 中的替换功能会引发 SettingWithCopyWarning?
- reactjs - 我如何使用带有'django'的反应路由器
- html - RobotFramework:未找到带有定位器的链接/列表
- asp.net-core - 如何在 Controller 中调用 DotNet Core API HealthCheck 探针,而不是在 Ctartup.cs 中设置
- python - 在单行中总结熊猫数据框
- c# - ColorZone 不会在 WPF MaterialDesign 中投影