首页 > 解决方案 > 当有多个间接级别时如何解释 volatile

问题描述

假设我有以下

struct my_struct ** value;

我明白两者之间的区别

struct my_struct volatile * other_value; // pointer is volatile

struct * volatile other_value; // what pointer points to is volatile

但有什么区别

struct my_struct * volatile * value;  // call this (1)

struct my_struct ** volatile value;  // call this (2)

说(1)表示值指向的指针是易失的,(2)表示值是易失的,它指向的指针和指针指向的数据不是易失的,这是否正确?还是我把它弄反了?

更普遍地考虑可能看起来像这样的东西

struct my_struct ***** volatile *** value

这个“系列”指针中的哪个指针是易失性指针?是被重定向的指针(这是正确的术语吗?)从值重定向 3 次还是 4 次?换句话说,volatile 是否总是在最正确的值/ptr/语句上运行(这里的正确术语是什么?)。

例如

struct my_struct ******** volatile value

意味着价值是不稳定的

struct my_struct ******* volatile * value

表示指向的指针值是易变的

struct my_struct ****** volatile ** value

表示value指向的指针指向的指针是volatile的。等等。我的理解正确吗?

编辑:我完全错了。volatile 适用于左侧而不是右侧。

标签: cpointersdeclarationvolatilevariable-declaration

解决方案


经验法则是限定符(volatile 或 const 等)坚持左侧的内容。

我明白两者之间的区别

struct my_struct volatile * other_value; // pointer is volatile

struct * volatile other_value; // what pointer points to is volatile
...或者我有它倒退?

你倒过来了。第一种情况使结构数据易失,第二种情况使指针本身易失。

struct my_struct ***** volatile *** value

这意味着左指针* volatile是 volatile 限定的。

通常,从右到左阅读 C 中的声明有助于:

  • other_value其他价值...
  • * other_value ...是一个指针...
  • struct my_struct volatile * other_value……到struct my_struct volatile

另请注意,愚蠢的是,C 允许将变量声明中的限定符放置在任何地方。意思是volatile int* x;int volatile* x;是等价的。为什么允许这样做没有合理的理由,一直都是这样。


推荐阅读