是否为逗号分隔的变量定义分配了所有关键字?

Are all keywords distributed for comma separated variable definitions?

在这样的陈述中

static int a, b, c;

static 是应用于所有 3 个变量的定义还是仅应用于第一个? volatilemutable.

等其他关键字呢?

如果不同关键字的规则不同,有何不同?

比如我知道const是分布式的,但是指针不是,e.g.

int * a, b;

相同
int * a;
int   b;

注意:我尝试使用 const 而不是 static 来问类似的问题,结果被误解了。我想知道根据标准,general 规则适用于 all 个适用关键字。

这么说吧。在变量类型说明符由多个单词后跟逗号分隔的变量列表组成的任何情况下,如何解析 definition/declaration?

所有初始类型词适用于所有变量,或者更准确地说,适用于声明符。声明符是声明中使用的伪表达式。

例如:

static int volatile long a, b[10], *&c, *(*const d)(float);
//^^^^^^^^^^^^^^^^^^^^^^
// typey words

//                       ^  ^^^^^  ^^^  ^^^^^^^^^^^^^^^^^^
//                       4 declarators

这里

  • a是一个static volatile long int
  • b 是 volatile long int
  • 的静态数组[10]
  • c 是指向 volatile long int
  • 的指针的静态引用
  • d 是指向函数的静态 const 指针(采用 float)返回指向 volatile long int
  • 的指针

(另外,开头打字的顺序无关紧要。)


参考文献:

在 C++98 (ISO/IEC 14882:1998) 中(过时了,我知道,但这部分语言从那时起并没有根本改变)我们有(所有强调我的):

[dcl.dcl]:

simple-declaration:
                   decl-specifier-seqopt init-declarator-listopt
;

[...]

  1. Each init-declarator in the init-declarator-list contains exactly one declarator-id, which is the name declared by that init-declarator and hence one of the names declared by the declaration. The type-specifiers (7.1.5) in the decl-specifier-seq and the recursive declarator structure of the init-declarator describe a type (8.3), which is then associated with the name being declared by the init-declarator.

(标准更喜欢术语“声明说明符”而不是“类型词”,但它是同一件事。)

这表示所有类型说明符都与每个声明符组合在一起,形成每个声明名称的类型。类型说明符包括 constvolatilesignedunsigned,以及所有基本类型(voidintwchar_t, ...) 和用户定义的 classenumtypedef 名称(参见 [dcl.type])。

类似的语言适用于存储class说明符,分别列出(autoregisterstaticexternmutable) 在 [dcl.stc]:

  1. [...] The storage-class-specifier applies to the name declared by each init-declarator in the list and not to any names declared by other specifiers. [...]

类似地,对于 typedef 我们有(在 [dcl.dcl]):

  1. If the decl-specifier-seq contains the typedef specifier, the declaration is called a typedef declaration and the name of each init-declarator is declared to be a typedef-name, synonymous with its associated type (7.1.3). [...]

后面关于声明符的章节([dcl.decl])总结了一般原则:

  1. The two components of a declaration are the specifiers (decl-specifier-seq; 7.1) and the declarators (init-declarator-list). The specifiers indicate the type, storage class or other properties of the objects, functions or typedefs being declared. The declarators specify the names of these objects, functions or typedefs and (optionally) modify the type of the specifiers with operators such as * (pointer to) and () (function returning). [...]

  2. Each init-declarator in a declaration is analyzed separately as if it was in a declaration by itself.

当前草案中的等效部分: