没有大小和 const volatile 声明的数组

Array declared without size and const volatile

我在我的工作项目中找到了这一行,但我无法理解:

extern const volatile uint8 * const volatile array[];

你能帮我解释一下这条线吗?

首先,省略限定符:

uint8 *array[];

array 是一个未指定大小的数组,其元素类型为 uint8 *。换句话说,指向 uint8 的指针数组。

如果此声明作为函数的参数出现,则数组语法实际上是 shorthand 指针。如果它不是函数参数并且在文件范围内声明,那么这将作为 暂定定义 。完整的定义可能出现在指定大小和可选的初始化程序的代码中的其他地方。如果不存在其他完整定义,则数组被定义为具有 1 个元素。

在讨论声明对限定符的含义之前,让我们先谈谈这些限定符的确切含义。

const 限定符防止代码修改命名对象。鉴于此声明:

const int x;

表示x不能修改,例如x = 1。涉及指针时,它有点棘手:

const int *x;

这将 x 定义为指向 const int 的指针。这意味着您可以修改 x 但不能修改它指向的内容。所以 x = &y 合法但 *x = 1.

不合法
int * const x;

这将 x 定义为指向 intconst 指针,这意味着您不能修改 x 但可以修改它指向的内容。所以 x = &y 不合法,但 *x = 1 合法。

const int * const x;

这将 x 定义为指向 const intconst 指针。所以在这种情况下,x 和它指向的内容都不能修改。

const int * const x[];

这里,x是一个数组,其元素是const个指向const int的指针。与前面的示例一样,对于每个数组元素,都不能修改数组元素及其指向的内容。

现在让我们谈谈volatile。该限定符告诉编译器所讨论的变量可能会发生不可预测的变化。来自 C standard 的第 6.7.3p7 节:

An object that has volatile-qualified type may be modified in ways unknown to the implementation or have other unknown side effects. Therefore any expression referring to such an object shall be evaluated strictly according to the rules of the abstract machine, as described in 5.1.2.3. Furthermore, at every sequence point the value last stored in the object shall agree with that prescribed by the abstract machine, except as modified by the unknown factors mentioned previously. 134) What constitutes an access to an object that has volatile-qualified type is implementation-defined

134) A volatile declaration may be used to describe an object corresponding to a memory-mapped input/output port or an object accessed by an asynchronously interrupting function. Actions on objects so declared shall not be "optimized out" by an implementation or reordered except as permitted by the rules for evaluating expressions

这意味着 volatile 对象可以以编译器不知道的方式更改,因此编译器不应对此变量执行任何优化,实际上应该假设该值已从外部更改。

现在开始您的完整声明:

const volatile uint8 * const volatile array[];

这将 array 声明为一个未指定大小的数组,其元素的类型为 uint8 *,其中数组的元素不能被程序修改(即 const)但可以在外部修改(即 volatile),并且这些数组元素指向的内容也不能被程序更改,但可以在外部修改。