Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 228
WilliamKF Avatar asked Aug 05 '19 16:08

WilliamKF


People also ask

What is the use of static keyword in C?

What is the use of static keyword in C? Let’s combine into one answer covering C and C++. static keyword behavior depends is it applied on global or local variables: Global - variables outside of function, class, struct, etc. When static variable scope is limited to the file where is defined.

What is a static variable in C?

Definition. The static keyword in C is a storage-class specifier. It has different meanings, depending on the context. Inside a function it makes the variable to retain its value between multiple function calls.

What is the opposite of static in C programming?

The opposite of static is the extern keyword, which gives an object external linkage. Peter Van Der Linden gives these two meanings in "Expert C Programming": Inside a function, retains its value between calls. At the function level, visible only in this file. There's a third storage class, register.

What does it mean when a function is declared as static?

This means that we cannot access a static function or variable from another source file. It is a good practice to declare most of your functions static. Leave visible only the functions that need to be accessed from other files.


2 Answers

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 [..]

like image 107
Lightness Races in Orbit Avatar answered Oct 16 '22 17:10

Lightness Races in Orbit


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.

like image 25
Vlad from Moscow Avatar answered Oct 16 '22 18:10

Vlad from Moscow