There are two issues here, lifetime and scope.
The scope of variable is where the variable name can be seen. Here, x is visible only inside function foo().
The lifetime of a variable is the period over which it exists. If x were defined without the keyword static, the lifetime would be from the entry into foo() to the return from foo(); so it would be re-initialized to 5 on every call.
The keyword static acts to extend the lifetime of a variable to the lifetime of the programme; e.g. initialization occurs once and once only and then the variable retains its value - whatever it has come to be - over all future calls to foo().
There are two issues here, lifetime and scope.
The scope of variable is where the variable name can be seen. Here, x is visible only inside function foo().
The lifetime of a variable is the period over which it exists. If x were defined without the keyword static, the lifetime would be from the entry into foo() to the return from foo(); so it would be re-initialized to 5 on every call.
The keyword static acts to extend the lifetime of a variable to the lifetime of the programme; e.g. initialization occurs once and once only and then the variable retains its value - whatever it has come to be - over all future calls to foo().
Output: 6 7
Reason: static variable is initialised only once (unlike auto variable) and further definition of static variable would be bypassed during runtime. And if it is not initialised manually, it is initialised by value 0 automatically. So,
void foo() {
static int x = 5; // assigns value of 5 only once
x++;
printf("%d", x);
}
int main() {
foo(); // x = 6
foo(); // x = 7
return 0;
}
Why wasn't the idea of a Static variable in a function more widely adopted?
Don't use a static variable inside a function in a class/struct. Is there a simpler alternative method?
How to make a local static variable like C has
syntax - What does "static" mean in C? - Stack Overflow
What is a static variable in C?
Why use static variables in C?
Can static variables be used in recursive functions?
Videos
I'm not a very experienced programmer, so maybe this is a stupid question.
As far as I understand when you want to add 'statefulness' to a function in most modern languages, you'd use a closure, but often this is kinda verbose: you need to define a function inside a function and capture over a variable.
'Static' in c achieves basically the same thing as a closure, but it's way more compact (and if you are not familiar with closures, easier to reason about). Why wasn't it adopted in newer languages?
In modern C++ you can define and initialise the member:
class Window
{
uint32_t mouseButtons_old = 0;
void Window::event(const vec2 &displaySize, SDL_Event &sdlEvent, bool wantCaptureMouse)
{
. . .
}
};
Viorel-1 > Thanks. I didn't know that method exists, I used it in a very far past but I forget. That's why forum is so helpful. I tried to Google the question before but there wasn't such answer. So thank you.
Usually, you will see the static keyword in these places:
- A static variable inside a function keeps its value between invocations.
- A static global variable or function is "seen" only in the file in which it's declared.
(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,
staticis used with global variables and functions to set their scope to the containing file. In local variables,staticis 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.
See here and here for more details.
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.
Additionally, in C, static can be used in array declarators to specify minimum size of the array (non-function array declarators cannot use this keyword). Consider this declaration:
void func(int foo[static 42]);
The function func() takes an array of at least 42 elements.
Note that C++ does not support this use of the static keyword.
There is one more use not covered here, and that is as part of an array type declaration as an argument to a function:
int someFunction(char arg[static 10])
{
...
}
In this context, this specifies that arguments passed to this function must be an array of type char with at least 10 elements in it. For more info see my question here.