What does static mean in C?
- A static variable inside a function keeps its value between invocations.
- A static global variable or a function is "seen" only in the file it's declared in
(1) is the more foreign topic if you're a newbie, so here's an example:
#include <stdio.h>
void foo()
{
int a = 10;
static int sa = 10;
a += 5;
sa += 5;
printf("a = %d, sa = %d\n", a, sa);
}
int main()
{
int i;
for (i = 0; i < 10; ++i)
foo();
}
This prints:
a = 15, sa = 15
a = 15, sa = 20
a = 15, sa = 25
a = 15, sa = 30
a = 15, sa = 35
a = 15, sa = 40
a = 15, sa = 45
a = 15, sa = 50
a = 15, sa = 55
a = 15, sa = 60
This is useful for cases where a function needs to keep some state between invocations, and you don't want to use global variables. Beware, however, this feature should be used very sparingly - it makes your code not thread-safe and harder to understand.
(2) Is used widely as an "access control" feature. If you have a .c file implementing some functionality, it usually exposes only a few "public" functions to users. The rest of its functions should be made static
, so that the user won't be able to access them. This is encapsulation, a good practice.
Quoting Wikipedia:
In the C programming language, static
is used with global variables and
functions to set their scope to the
containing file. In local variables,
static is used to store the variable
in the statically allocated memory
instead of the automatically allocated
memory. While the language does not
dictate the implementation of either
type of memory, statically allocated
memory is typically reserved in data
segment of the program at compile
time, while the automatically
allocated memory is normally
implemented as a transient call stack.
And to answer your second question, it's not like in C#.
In C++, however, static
is also used to define class attributes (shared between all objects of the same class) and methods. In C there are no classes, so this feature is irrelevant.
Difference between static variables and static array variables
A variable declared at block scope as static
, or at file scope, has static storage duration and matches the lifetime of the program. This is equally true for arrays and non-arrays.
Arrays cannot have their size changed in any case . The size specified in the declaration is the size of the array for its lifetime .
If you are talking about the keyword static
inside square brackets of an array declarator in a function parameter (e.g. void f(int x[static 2]);
) then this is an entirely different thing (the same keywords has been reused for unrelated purposes) and it means the function may be optimized as if it were only called with an array of at least that size.
Difference between static function and non static function in C
There is absolutely no performance difference. The the only thing the static
keyword does on functions is given them internal linkage, which means they are only accessible in the file they are defined in.
static volatile' vs. 'static' vs. 'volatile' in C
static - in this case makes the variable visible only inside the current file
volatile - it is information for the compiler that the object can be changed by something outside the normal execution path (for example, the interrupt routine) and guarantees that the variable will be read before any use and written after every change. volatile (which is a very common misunderstanding) does not guarantee anything else - no atomicity, no cache coherency, etc., etc.
Difference between static global variable and non-static global variable in C
There are basically four cases:
- declared outside of function, without
static
- declared outside of function, with
static
- declared inside of function, without
static
- declared inside of function, with
static
Let's cover these in turn.
Declared outside of function, without static
This is a conventional global symbol. You can access it from any source file (although in that other source file, you typically need an extern
declaration).
Declared outside of function, with static
This is the "static" global you were asking about. You can access it only within the source file where it is defined. It's "private" to that source file, but you can access it from any function in that source file (well, actually, any function in that source file that occurs below its declaration). Like any global variable, it maintains its value for the life of the program.
Declared inside of function, without static
This is a conventional local variable. You can access it only within that function. Each time the function is called (including recursively), you get a new instance of the variable. If you don't initialize it, it starts out containing an unpredictable value. It does not maintain its value between calls.
Declared inside of function, with static
This is a static local variable. You can access it only within that function. There is exactly one copy of it, shared between all calls to the function (including recursive calls). If you don't initialize it, it starts out zero. It maintains its value between calls.
In three of these cases, if you don't provide an explicit initializer, a variable is guaranteed to be initialized to 0. But in the case of true local variables, if you don't provide an explicit initializer,
it starts out containing an unpredictable value, which you can't depend on.
Formally, there are two concepts here, visibility and lifetime. True global variables are visible anywhere in the program. Static global variables are visible only in their source file. Local variables are visible only in their function. All global variables, and all static variables, have static duration — they last for as long as the program does. (Also these are the ones that are guaranteed to be initialized to 0.) True local variables have "automatic" duration — they come and go as the containing function is called and returns.
Closely related to duration is the question of where variables will actually be stored. Static-duration variables are typically stored in the data segment. Automatic-duration variables are typically — though not necessarily — stored on the stack.
What is the difference between a static variable in C++ vs. C#?
Static has multiple meanings in C++.
Static variables in C# basically only have a single meaning: variables scoped to a type. In C#, static on a type is used to denote a type-scoped variable. Static on a method is a type-scoped method. Static can also be used on a class to denote that the entire class is comprised only of static methods, properties, and fields.
There is no equivelent to static variables within a function scope, or non-class scoped static values.
Edit:
In reponse to your edit, C# basically only uses static for class members. Globals and local static function variables are not supported in C#. In addition, as I mentioned above, you can flag an entire class "static", which basically just makes the compiler check that there are no non-static members in the class.
Related Topics
How to Test Whether Class B Is Derived from Template Family of Classes
Boost C++ Regex - How to Get Multiple Matches
How to Invoke a User-Defined Conversion Function via List-Initialization
Programmatically Check Whether My MAChine Has Internet Access or Not
Std::Filesystem' Has Not Been Declared After Including <Experimental/Filesystem>
Boost::Spirit::Qi Parser: Index of Parsed Element
Is Using an Union in Place of a Cast Well Defined
Passing a C++ Complex Array to C
What's the Best Hashing Algorithm to Use on a Stl String When Using Hash_Map
Is Substitution Performed on a Variadic Parameter Pack Type If the Pack Is Empty
Static Member Variable in a Class
Removing Duplicate Characters from String Using Stl
Line by Line C - C++ Code Debugging in Linux Ubuntu
Pointer Comparisons ">" with One Before the First Element of an Array Object
Getting Input from User Using Cin
Rc.Exe No Longer Found in VS 2015 Command Prompt
Why Is This Simd Multiplication Not Faster Than Non-Simd Multiplication
Knight's Tour Backtrack Implementation Choosing the Step Array