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?
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.
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.
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.
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.
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 [..]
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With