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.
Related
My C is quite rusty, please help me out.
static int i = 42;
int main()
{
}
creates a variable i with global scope and internal linkage. Meaning anyone can refer to it but only entries within the translation unit(.c file) will not break the linker. It is allocated during program linking and is initialized before main() is entered.
void foo()
{
static int i = 69;
}
creates a variable with function scope and no linkage. Meaning nothing outside of foo() can refer to it and even if the compiler didn't cry out, taking the address of this (essentially protected global) variable is UB. It is allocated during program linking and is initialized when foo() is first called.
Please correct me!
creates a variable i with global scope and internal linkage. Meaning anyone can refer to it but only entries within the translation unit(.c file) will not break the linker. It is allocated during program linking and is initialized before main() is entered.
Correct, except the formal term is file scope (outside any function), not to mixed up with "global" which can often mean accessible everywhere. In this case the variable is declared at file scope but it is not "globally" accessible. Generally, the informal term "global" is used together with the formal term external linkage and usage of the extern keyword.
creates a variable with function scope and no linkage.
No, it creates a variable with block scope. There exists a formal term function scope but it refers to the scope of goto labels. C has four scopes: file scope, function scope, block scope and function prototype scope. Those who aren't language lawyers or spaghetti programmers only need to know about file scope and block scope.
Meaning nothing outside of foo() can refer to it
Correct.
even if the compiler didn't cry out, taking the address of this (essentially protected global) variable is UB
No, this is wrong. Scope doesn't determine if a variable can be accessed or not, storage duration does. Both your examples declare variables with the same static storage duration but with different scopes. A variable with static storage duration persists and remains valid throughout the execution of the program.
Therefore it is fine and well-defined to return a pointer to a block scope variable with static storage duration. (It may not be thread-safe however, but that's another story.)
It is allocated during program linking
Correct.
and is initialized when foo() is first called.
No, this is wrong. All variables with static storage duration, regardless of their scope, are initialized before main() is called. Either to an explicit initializer as in your examples (typically meaning it gets allocated in a segment named .data) or to zero in case it wasn't explicitly initialized (all static storage variables set to zero typically gets allocated in a segment named .bss).
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.
If static local variable also stored in the data segment, why can't values are not persist for variable which is used in two different functions. example like this.
void func()
{
static int i=0;
i++;
}
void func1()
{
i++; // here i is stored in the data segment,
// then the scope should be available for entire program
}
Why the value 'i' is only accessible to block scope if is stored in data segment? it might be a silly question but I am trying to understand to concept. Please help me to understand concept. Thanks in advance.
You need to differentiate between the scope and the lifetime of a variable.
In simple words:
"scope" means the region of your source code where the variable is known to the compiler. If a variable is (by the rules) not visible to the compiler, it will refuse to compile accesses to it.
"lifetime" means the time beginning with the allocation of memory for the variable until the moment the memory is assigned to another variable or released. A static variable lives as long as the program runs. A non-static variable lives just as long as its scope is in control.
However, just because both scope and lifetime of a variable are "finished", that does not mean that the memory disappears. The physical cells are still there, and they keep their last contents. That's why you can program functions that return a pointer to some local variable, and retrieve that variables contents after both the scope and the lifetime of the variable are gone. This is a fine example of a beginner's confusing issue.
Consider a compiler for an embedded processor like the 8051. Granted, a quite old and simple machine, but a good example. This compiler will commonly put local variables in its data segment. But to use the limited memory space (128 bytes in total, including working registers and stack) the same memory locations are re-used for variables with non-overlapping lifetimes. Eventhough, you could access any memory from all of the program.
Now, language lawyers, start picking on me. ;-)
A variable in C consists of two things:
A name, called an identifier. An identifier has a scope, which is a region of the program source code in which it is visible (may be used).
A region of storage (memory), called an object. An object has a lifetime, which is a portion of program execution during which memory is reserved for it. This is also called storage duration.
For a variable declared inside a function, its identifier has block scope, and the identifier is visible only from its declaration to the } that closes the innermost block it is in. (A block is a list of statements and declarations inside { and }.)
Inside a function, declaring a variable with static makes its object have static storage duration, causing it to exist for all of program execution, but it does not change the scope of its identifier. The object exists throughout program execution, but the identifier is visible only inside the function.
When another function is called, the object still exists (and it can be used if the function has its address, perhaps because it has been passed as a parameter). However, the identifier for the variable is not known inside the source code of other functions, so they cannot use the identifier.
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.
I know there are three types of static declerations in C:
1: Constant - constant static variable, ex: static const int i = 5;
2: Changable - just a normal static variable, ex: static int hi = 10;
Here is my question
There is another form of static which takes the form of "code". What does that mean and can you give me an example?
Thank you!
EDIT:
Are static/const variables stored on the stack/heap?
Maybe you are talking about a static function ?
This is a specific use of the word "static", which is entirely different from a static variable.
When you declare a function "static", that means it cannot be linked from another source file. It is typically used to keep some functions "private".
[Edit] Note that, in theory, the function code could still be accessed from another source file using pointers, but that's not quite the normal way (and certainly not the easiest) to access a function. Thanks to Eric Postpischil for pointing that out.
It's unfortunate that the same word "static" is used in the C standard to mean two different things, depending on being used for functions or variables.
[edit] : It's a different question, but anyway : in the case of static variables, they are neither allocated in the heap nor the stack. They are, well, static, which means they are allocated in a static space, directly allocated by the compiler at startup. Stack is for internal functions variables, and heap is for malloc()/free().
This link should answer your question.
It is however worth noting that unless you have sufficient knowledge of the C compilation process this will be of questionable value.
A good reference for GCC can be found here.
I believable you're asking about static functions.. So..
Static functions
By default, functions in C are extern, meaning that the function can be used in any other file of the same project (and the same code of course).
If you don't like this situation and you want to limit the function to the file in which it's defined, you make it static.
The keyword static is used in several different ways in C. (There's a joke that any new version of the ISO C standard is required to invent a new meaning for static.)
Quick summary: The static keyword on a block scope definition gives the entity static storage duration; at file scope, where definitions already have static storage duration, it instead gives them internal linkage.
An object may have any of several storage durations. An object with "automatic" storage duration exists at run time only during the execution of the enclosing block. An object with "static" storage duration exists during the entire execution of the program. (There are also "allocated" and, new in C11, "temporary" storage durations, which I won't get into.)
Any definition of an identifier also has a "linkage", which can be external, internal, or none. Linkage controls whether an identifier is usable across translation units (basically source files, but #included files are not separate translation units). Linkage, as the name implies, has to do with the linker. You can use the same identifier with internal linkage in two different source files, and it will refer to two different entities. But if an identifier has external linkage, it should be defined only once, and can be declared (typically with extern) in multiple source files; all those declarations will refer to the same entity.
If you define an object (variable) at block scope, (i.e., inside a function body), it has automatic storage duration (and no linkage) by default. Adding the keyword static gives it static storage duration, so it exists and retains its value across calls to the function. (It doesn't affect the identifier's visibility).
If you define an object at file scope (i.e., outside any function body), it has static storage duration and external linkage by default. Adding the keyword static to the definition doesn't affect its storage duration, but it changes its linkage from external to internal, hiding the name from other translation units. Functions don't have storage duration (their code exists as long as the program is running), but static affects their linkage the same way, changing it from external to internal.
(C99 added another meaning for static, for function parameters of array type, which has nothing to do with the other uses.)
I think it's worth to clarify what we're talking about and try to use the correct wording.
The const qualifier has nothing to do with the static keyword.
Technically, the static keyword appears in declarations and it's usually a storage-class specifier, but from C99 it can also be in array declarators, though this is quite unusual.
When it's a storage-class specifier, just like in the declarations you've posted, it affects the linkage (visibility between files) of the identifier and the storage duration (lifetime) of the identified object, but not the scope of the identifier.
6.2.2 Linkages of identifiers
[...] Within one translation unit, each declaration of an identifier with internal linkage denotes the same object or function. [...]
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.30)
30) A function declaration can contain the storage-class specifier static only if it is at file scope; see 6.7.1.
Therefore, the identifier can only be seen in the translation unit (i.e., a source file after the preprocessing) where it's declared, whether it's an object or a function (maybe that's what you were looking for). So you can use to declare "private" functions to be used in just one file.
static void foo(void)
{
// ...
}
The static keyword it's also used with the inline function specifier, which has a particular linkage semantics: https://stackoverflow.com/a/216546/1202636
Obviusly when we are not at file scope but in a more restricted one (static declarations inside functions) the linkage question becomes irrelevant since such an identifier has no linkage at all.
6.2.4 Storage durations of objects
An object whose identifier is declared [...] either with external or internal linkage or with the storage-class specifier static, has static storage duration. Its lifetime is the entire execution of the program and its stored value is initialized only once, prior to program startup.
This one only applies to object identifiers and it affects the lifetime of the object, for example letting a variable retains its value between calls, and its initialization.
(just to say it, such an object is also initialized with a default value)
As I said, there's a less common use of the static keyword: it can be use in array declarators inside function prototypes, to tell the compiler that an array given as parameter contains at least n elements. This is a (modified) example from the standard:
void f(double a[static 3][5]);
The declaration specifies that the argument corresponding to a in any call to f must be a non-null pointer to the first of at least three arrays of 5 doubles, which the others do not.
.
Are static/const variables stored on the stack/heap?
Again, the constness has nothing to do with the place where an object is stored. The standard doesn't say anything about that place, there's usually a dedicated area but this is a different and already answered question: where are static buffers allocated?
Are static/const variables stored on the stack/heap?
Well, no, they are part of the "global" space.
Stack and Heap are for "dynamic" memory allocation, not static !