13

In C++, if I have a class:

class Example {
  static int s_One, s_Two;

  ...
};

Does the language clearly define that s_Two is also static?

In other words, does the static keyword extent go everywhere the int goes, or can it be like * and only apply to one variable?

curiousguy
  • 8,038
  • 2
  • 40
  • 58
WilliamKF
  • 41,123
  • 68
  • 193
  • 295
  • 1
    This question can be answered by reading [the standard](http://eel.is/c++draft/). But, why don't you simply remove the ambiguity by declaring each variable on its own? – Jesper Juhl Aug 05 '19 at 16:43
  • 13
    @JesperJuhl: Arguably, most answers about C++ can be answered by reading the standard. But the standard is big and sometimes difficult to navigate. – rodrigo Aug 05 '19 at 16:46
  • @JesperJuhl The answer might also be valuable to other people. – ruohola Aug 05 '19 at 17:19
  • it would be pretty stupid to not apply all the declarators to all the variables introduced by the declaration... "C++: hold my beer `int* a, b`" – bolov Aug 11 '19 at 22:41

2 Answers2

20

Yes, it applies to every name in that declaration:

[dcl.stc]/1: [..] At most one storage-class-specifier shall appear in a given decl-specifier-seq [..] The storage-class-specifier applies to the name declared by each init-declarator in the list [..]

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
2

According to the C++ 17 Standard (10 Declarations)

2 A simple-declaration or nodeclspec-function-declaration of the form

attribute-specifier-seqopt decl-specifier-seqopt init-declarator-listopt ;

And (10.1 Specifiers):

1 The specifiers that can be used in a declaration are

decl-specifier:
    storage-class-specifier
    ...

So in this declaration

static int s_One, s_Two;

the decl-specifier-seq contains two decl-specifiers, static (storage class specifier) and int. Thus the storage class specifier static describes the both variables in the init-declarator-list s_One and s_Two.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335