What the word "static" in static class means? - static

I know what static classes are I would like to know more about the word "static".
When I search for the word "static" I get many definitions, from most of them I get that static is something that doesn't move (fixed in place). Is it right?
What does the word mean? Where did the word came from historically?
Thank you in advance.

Static is a keyword used to give special characteristics to an element. Static elements are allocated storage only once in a program lifetime in static storage area. And they have a scope till the program lifetime. Static Keyword can be used with following, Static variable in functions.
In the C programming language (and its close descendants such as C++ and Objective-C), static is a reserved word controlling both lifetime (as a static variable) and visibility (depending on linkage). The word static is also used in languages influenced by C, such as Java.
In C, static is a storage class (not to be confused with classes in object-oriented programming), as are extern, auto and register (which are also reserved words). Every variable and function has one of these storage classes; if a declaration does not specify the storage class, a context-dependent default is used:
extern for all top-level declarations in a source file,
auto for variables declared in function bodies.
Storage class Lifetime Visibility
extern program execution external (whole program)
static program execution internal (translation unit only)
auto, register function execution (none)
In these languages, the term "static variable" has two meanings which are easy to confuse:
A variable with the same lifetime as the program, as described above (language-independent); or
(C-family-specific) A variable declared with storage class static.
Variables with storage class extern, which include variables declared at top level without an explicit storage class, are static in the first meaning but not the second.
The static keyword when prefixed while declaring a variable or a function can have other effects depending on where the declaration occurs.
Static global variable
A variable declared as static at the top level of a source file (outside any function definitions) is only visible throughout that file ("file scope", also known as "internal linkage").
Static local variables
Variables declared as static inside a function are statically allocated, thus keep their memory cell throughout all program execution, while having the same scope of visibility as automatic local variables (auto and register), meaning remain local to the function. Hence whatever values the function puts into its static local variables during one call will still be present when the function is called again.
Static member variables
Member variables declared as static inside class definitions are class variables (shared between all class instances, as opposed to instance variables).
Static function
Similarly, a static function -- a function declared as static at the top level of a source file (outside any class definitions) -- is only visible throughout that file ("file scope", also known as "internal linkage").
Static method
Similarly, a static method -- a method declared as static inside a class definition -- are meant to be relevant to all instances of a class rather than any specific instance.

Related

Why and where to use a global variable and a static global variable in C?

I have read about global and local variables and static keyword, but i dont know which is the difference between something like this:
int x; //Global variable
int main(){
//Code...
}
And this:
static int x; //Static Global variable
int main(){
//Code...
}
I know some properties of the static keyword, and i know why is useful for local variables, but i dont know which is the use for global variables
I have read that using static for global variables is used for accesing the variable only in the C file it is declared/defined, but, i mean, if we dont use extern we just cant access that global variable in other c files anyway
I think that a "static global" variable is used to prevent the use of the extern keyword in order to prevent the use of that variable in multiple C files, is that correct?
Thanks in advance!
"Global" is not a formal term, but it generally means "variable that can be accessed anywhere". Therefore global.
To dive into some formal terms:
The formal and correct term for a variable declared outside a function is declared at file scope.
What formally defines how a variable may be accessed in C is referred to as linkage.
A variable declared at file scope generally has external linkage and can be referred to from elsewhere with extern.
So the correct term to use for your first example is "file scope variable with external linkage".
Whenever we add the storage class specifier static to a declaration, we force the variable or function to instead get internal linkage. This means that it is only accessible from within the translation unit (the .c file and all .h files it includes) where it was declared.
It is the opposite of global, so saying "static global" doesn't make any sense. You cannot refer to such a variable with extern. Instead the correct term is "file scope variable with internal linkage".
The main purpose of static is indeed private encapsulation, since the internal linkage guarantees that the variable or function cannot be accessed by other .c files.
But static also at the same time gives static storage duration to a variable, meaning it is guaranteed to persist throughout the execution of the program and that it has some initialization rules guaranteed. Now as it happens, variables at file scope always gets static storage duration, static or not, so it isn't very relevant to your example. But as you earlier discovered, static storage duration does make a big difference for local variables, since their value will then be preserved throughout multiple function calls.
More details here: What does the static keyword do in C?
Yes, it is correct.
A global static variable can only be accessed in the file where it is created (file scope).

Whether Global Variables in C, static or extern?

I just started learning C programming.
In some of the books and web articles, I could find that any Global Variable in C by default corresponds to static storage class but has external linkage.
Does this mean it is partially static and partially extern? Because as per my understanding any global variable with static storage class specifier has internal linkage only and can be accessed within the same file.
P.S: I referred this question Global variables in C are static or not? , but could not get really whether Global variables are static or extern by default in C.
Global Variable in C by default corresponds to static storage class but has external linkage. Does this mean it is partially static and partially extern?
The English word “static” has muddled and multiple meanings in C, and, yes, the default for a variable declared outside a function is to have static storage duration and external linkage.
Because there are multiple concepts here and some mixed use of word meanings, we should clarify some terminology and formatting:
Use code style to refer to specific text in source code, such as the keyword static. When speaking of static storage duration or external linkage, “static” and “external” are mere English adjectives and should not be in code style.
“Global” means visible throughout an entire program. The C standard does not use this word for this purpose. It uses “external” to refer to things that are outside of (external to) any function. (But it also uses “external” for other purposes.) A global variable could not have internal linkage, because it would not be visible throughout the entire program.
A variable consists of an object (memory reserved for representing the value) and an identifier (the name). Storage duration is a property of the object. Linkage is a property of the identifier.
The English word “static” generally means unchanging. The C standard uses this word and the keyword static in multiple ways:
Static storage duration means the memory for an object is reserved throughout all of program execution.
Using the static keyword in a declaration, other than as below, both gives an object static storage duration and, in a declaration outside a function, gives the identifier internal linkage.
Using the static keyword inside subscript markers in a parameter declaration, as in void foo(int a[static 3]), indicates that the parameter points to at least the stated number of elements.
Static assertions, using _Static_assert, provide compile-time tests (which can help detect bugs or ensure a program is being compiled with expected settings).
These multiple uses are unfortunate and are due at least partly to the history of how the C language was developed.
Whenever you don't intend to use a variable declared in one file in a Different file the you should use static keyword before the declaration
file1.c:
static int number = 63; // this variable is used only in this file
...
file2.c:
float brightness = 0.5; // is needed in some Other file;
...
file3.c:
extern float brightness; // use external declaration to use it here
...
When ever possible, you should use the static variables.
If you want to use two global variables in two different translation units (c files) then your compiler will throw an error saying that the variable is already declared elsewhere.
Using static will make it hidden for other translation units.
You mix up static and static storage duration.
Storage duration and linkage are different terms. There is nothing in C called "global", though the term is often sloppily used for any variable declared at file scope - that is: outside any function. More correct use of the term "global" would be that the variable has external linkage, meaning it may be referred to anywhere in the whole project.
All variables declared at file scope have static storage duration. This dictates how such variables are initialized and that they persist throughout the whole exeuction of the program (practically, it likely also means that the variable ends up in .data or .bss segments of the implementation).
A variable declared at file scope but without any storage class specifier (neither static nor extern) has external linkage, but it still got static storage duration. From 6.2.4:
If the declaration of an identifier for an object has file scope and no storage-class specifier, its linkage is external.
But if you add a storage class specifier to a file scope variable, you specify both storage duration and linkage. 6.2.4/3:
If the declaration of a file scope identifier for an object or a function contains the storage-class specifier static, the identifier has internal linkage.
And as you say, a variable with internal linkage can only be referred to from the same file (strictly speaking same "translation unit").
There's some subtle difference here in case you add static to a local variable - it then specifies storage duration but not linkage. The whole term linkage is rather confusing - simply put the purpose of the term is to dictate when two variables with the same name refer to the same object or different ones. This is mostly a concern for those making compilers/linkers as well as for spaghetti programmers. Avoid belonging to the latter category by following the advise below.
Beginners need not worry about any of the above.
Rules of thumb for beginners:
Never declare variables outside functions unless they are static.
Never declare variables in header files.
Never use extern.
Use static in front of functions if they aren't meant to be called from other files.
This will get you very far, and the rare cases where you actually need to share variables between different files is another story/advanced topic.

Static global in memory

If there are 2 files in a project, using same name for static variable in both files, I didn't get linker error, but I want to know how two static variables named in memory.
Static variables are not visible outside the C file where they are declared (or even outside the scope, with "C file" being "a particular file's file scope"). So there is no collision, and of course variable names don't matter in compiled code.
The static variable is visible only within the module, it provides the local linkage.
The static variable inside the function it retains the value during function call.
The Static global variable or the function is visible only in the file or module that is declared.
The static specifier specifies both static storage duration and internal linkage.
Static storage duration. The storage duration is the entire execution of the program, and the value stored in the object is initialized only once, prior to main function.

Static storage class

I am the beginner in C and I am currently learning Data types revised chapter. I have solved many programs of static storage class. Static storage class has a local scope. In the below code the static variable is declared above main i.e global variable. Is this possible ? And the o/p according to features of static storage class is correct.
static int y ;
main( )
{
static int z ;
printf ("%d %d", y, z ) ;
}
Can anyone please let me know that the declaration of static variable above main is correct ? If this is correct please try to explain in layman language.
Storage class and scope are different things. The static keyword does not affect scope.
Storage class is related to the lifetime or storage duration of an object: When it is created and when its lifetime ends. Unfortunately, there is some mixing of storage class and other concepts, due to historical reasons. Storage class has some connotations about where something is stored. C has evolved so that the decision about where something is stored is largely up to the implementation. Usually, the programmer should only care about when something is stored.
Storage class is a property of an object: The actual thing (value) being stored. Scope is a property of an identifier: The name used to refer to an object (or a type or a function).
There are four storage durations: static, thread, automatic, and allocated. There are four kinds of scopes: function, file, block, and function prototype. The rules for them are somewhat complicated (and also depend on linkage, which can be external, internal, or none), so I will not describe them all.
If you define an object to be static, its lifetime is the entire execution of the program. By default, an ordinary object declared inside a function body has automatic storage duration. Its lifetime is from the time program execution enters the block it is in until program execution exits the block it is in. Each time execution enters the block, a new instance of the object is created. As you can see, lifetime is a property that applies when a program is running.
When you declare an object inside a function body, the identifier (name) in the declaration has block scope. The name is only visible inside the block. Scope is a compile-time property; it affects what parts of the source code can see the name. For example, if your function A calls function B at run-time, function B cannot see the names inside function A. Even though the objects in function A exist (a run-time property) while function B executes, their names (a compile-time property) are not visible in function B.
A name inside a function body has block scope, but it can refer to an object with automatic (block) storage duration or to an object with static (entire program) storage duration.
When you declare an object outside a function body, its identifier has file scope. It is visible to all following source code in the file.
There is also a property called linkage. Linkage is a method by which the same identifier in different scopes can be made to refer to the same object. (The foo in one source file can be made to refer to the same object is the foo of another source file.)
y is a global variable, but since it is declared static, it is only visible in the compilation unit, i.e. this same C-file. It will not be accessible from other units if you are compiling multiple objects and linking them together.
In this simple example it is not relevant whether a global variable is declared static.

Why declare a variable or function static in C?

I understand what static does, but not why we use it. Is it just for keeping the abstraction layer?
There are a few reasons to use static in C.
When used with functions, yes the intention is for creating abstraction. The original term for the scope of a C source code file was "translation unit." The static functions may only be reached from within the same translation unit. These static functions are similar to private methods in C++, liberally interpreted (in that analogy, a translation unit defines a class).
Static data at a global level is also not accessible from outside the translation unit, and this is also used for creating an abstraction. Additionally, all static data is initialized to zero, so static may be used to control initialization.
Static at the local ("automatic") variable level is used to abstract the implementation of the function which maintains state across calls, but avoids using a variable at translation unit scope. Again, the variables are initialized to zero due to static qualification.
The keyword static has several uses; Outside of a function it simply limits the visibility of a function or variable to the compilation unit (.c file) the function or variable occurs in. That way the function or variable doesn't become global. This is a good thing, it promotes a kind of "need to know" principle (don't expose things that don't need to be exposed). Static variables of this type are zero initialized, but of course global variables are also zero initialized, so the static keyword is not responsible for zero initialization per se.
Variables can also be declared static inside a function. This feature means the variable is not automatic, i.e. allocated and freed on the stack with each invocation of the function. Instead the variable is allocated in the static data area, it is initialized to zero and persists for the life of the program. If the function modifies it during one invocation, the new modified value will be available at the next invocation. This sounds like a good thing, but there are good reasons "auto" is the default, and "static" variables within functions should be used sparingly. Briefly, auto variables are more memory efficient, and are essential if you want your function to be thread safe.
static is used as both a storage class specifier and a linkage specifier. As a linkage specifier it restricts the scope of an otherwise global variable or function to a single compilation unit. This allows, for example a compilation unit to have variables and functions with the same identifier names as other compilation units but without causing a clash, since such identifiers are 'hidden' from the linker. This is useful if you are creating a library for example and need internal 'helper' functions that must not cause a conflict with user code.
As a storage class specifier applied to a local variable, it has different semantics entirely, but your question seems to imply that you are referring to static linkage.
Static functions in C
In C, functions are global by default. The “static” keyword before a function name makes it static. For example, below function fun() is static.
static int fun(void)
{
printf("I am a static function ");
}
Unlike global functions in C, access to static functions is restricted to the file where they are declared. Therefore, when we want to restrict access to functions, we make them static. Another reason for making functions static can be reuse of the same function name in other files.
For example, if we store following program in one file file1.c
/* Inside file1.c */
static void fun1(void)
{
puts("fun1 called");
}
And store following program in another file file2.c
/* Iinside file2.c */
int main(void)
{
fun1();
getchar();
return 0;
}
Now, if we compile the above code with command gcc file2.c file1.c, we get the error undefined reference to fun1. This is because fun1 is declared static in file1.c and cannot be used in file2.c. See also the explanation here, where the codes come from.

Resources