gpt4 book ai didi

c - 指针的 "volatile"属性是继承的吗?

转载 作者:行者123 更新时间:2023-11-30 14:24:22 26 4
gpt4 key购买 nike

假设我有以下代码:

my_struct_member_type *foo() {
volatile my_struct *s = (my_struct *)SOME_ADDRESS;
return &(s->struct_member);
}

foo 返回的指针也是 volatile 的吗?

编辑:后续:指针 &(s->struct_member) 在 foo 内部是否易失?

最佳答案

是的。

对于 volatile my_struct *s表示您通过它看到的对象是 volatile ,并且您通过此指针访问的所有成员都继承了 volatile > 资质。

如果返回类型没有说明,则返回指向 volatile 的指针的地址是违反约束的行为,并且您的编译器必须已经为您提供了诊断.

编辑: volatile 关键字的适用范围似乎也很困惑。在您的示例中,它适用于指向的对象,而不是指针本身。根据经验,始终将限定符(constvolatile)尽可能写在右侧,而不更改类型。您的示例将显示为:

my_struct volatile*s = (my_struct *)SOME_ADDRESS;

这与

完全不同
my_struct *volatile s = (my_struct *)SOME_ADDRESS;

其中指针本身是 volatile ,但其背后的对象不是。

编辑2:既然你要求我的来源,实际的C标准,C11,6.8.6.4它说的是return语句:

If the expression has a type different from the return type of the function in which it appears, the value is converted as if by assignment to an object having the return type of the function

6.15.16.1 对于赋值运算符,转换的预期结果是:

the left operand has atomic, qualified, or unqualified pointer type, and (considering the type the left operand would have after lvalue conversion) both operands are pointers to qualified or unqualified versions of compatible types, and the type pointed to by the left has all the qualifiers of the type pointed to by the right;

此处,除了左侧的指向类型之外,右侧的指向类型还具有 volatile 限定符。

关于c - 指针的 "volatile"属性是继承的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11860079/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com