What does C++ language definition say about the extent of the static keyword?
Asked Answered
A

2

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?

Austronesia answered 5/8, 2019 at 16:38 Comment(4)
This question can be answered by reading the standard. But, why don't you simply remove the ambiguity by declaring each variable on its own?Altruistic
@JesperJuhl: Arguably, most answers about C++ can be answered by reading the standard. But the standard is big and sometimes difficult to navigate.Prolong
@JesperJuhl The answer might also be valuable to other people.Turgid
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"Shanell
A
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 [..]

Atman answered 5/8, 2019 at 16:50 Comment(0)
P
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.

Perl answered 5/8, 2019 at 16:45 Comment(8)
That's not enough; this doesn't show that the SCS applies to both, just that is possible.Karrah
I'd still write static int s_One; static int s_Two;. Much more readable and unambiguous.Altruistic
@JesperJuhl No, this is invalid C++ syntax.Perl
No, it is not. Why do you say it is invalid?Chopping
@VladfromMoscow why?Rapp
@VladfromMoscow How is declaring two separate static ints invalid syntax?Altruistic
@Chopping I did not see that there is a semicolon instead of comma.:)Perl
@Karrah What is not enough for you?Perl

© 2022 - 2024 — McMap. All rights reserved.