1387

I've seen the word static used in different places in C code; is this like a static function/class in C# (where the implementation is shared across objects)?

jww
  • 97,681
  • 90
  • 411
  • 885
  • 9
    Related: [Static (keyword) @ Wikipedia](https://en.wikipedia.org/wiki/Static_%28keyword%29) – Palec Feb 06 '15 at 13:31
  • 42
    What is the reason to remove "in a C program" from the end of the title, @Lundin? It is slightly redundant in the presence of tag [tag:c], but it lets me see the categorization more quickly, without inspecting the tags. This redundance is very comfortable when I reach the question from a direction that may contain questions about other languages, too, e.g. [tag:static] or Google search. – Palec May 22 '17 at 14:55
  • 7
    @Lundin I prefer to keep "C" in the title, because SO only appends one tag to the title (the most common?). What if some day "syntax" reaches more questions than C (since it is a cross language thing)? I'd rather use the explicit behavior :-) Edit: ah but there is a meta question saying otherwise: https://meta.stackexchange.com/questions/19190/should-questions-include-tags-in-their-titles – Ciro Santilli OurBigBook.com Jun 17 '17 at 10:46
  • 3
    [This is an explanation I found on Quora.](https://www.quora.com/What-is-the-difference-between-int-and-static-int-data-types-in-C/answer/Rodolfo-Martinez-III?srid=kSgI) Definitely worth reading! – nalzok Aug 27 '17 at 13:45
  • 1
    Storage duration of static is until the program ends, instead of until the scope ends. –  May 14 '20 at 18:20
  • Related: [What is a “static” function in C?](https://stackoverflow.com/questions/558122/what-is-a-static-function-in-c) – RobertS supports Monica Cellio Jun 07 '20 at 18:20
  • @CiroSantilliOurBigBook.com It now does say "syntax - What does...." – Zak May 02 '23 at 01:47

21 Answers21

1834
  1. A static variable inside a function keeps its value between invocations.
  2. 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.

ady_agar
  • 3
  • 3
Eli Bendersky
  • 263,248
  • 89
  • 350
  • 412
  • 187
    Pax, the OP doesn't know about static, so you suggest plunging him into the difference between compilation units and files ? :-) – Eli Bendersky Feb 21 '09 at 07:08
  • 149
    A compilation unit is a single file the compiler sees. Your .c file may include other .c files, but after the preprocessor sorting out the includes, the compiler eventually sees just a single "compilation unit". – Eli Bendersky Feb 21 '09 at 07:12
  • 3
    David, if you're new to C, this issue shouldn't bother you at all. It doesn't bother 99.9% of C programmers anyway. – Eli Bendersky Feb 21 '09 at 07:13
  • 4
    so if you define a static in one header file that you include into a file, but in that file define the same static another time, it is an error, because the two definitions appear in the same translation unit. – Johannes Schaub - litb Feb 23 '09 at 13:00
  • 2
    This has got me thinking. Does the compilation unit consist of only its *.c file. For example, if I have a file called foo.c and a header called foo.h. Would the 2 of them consist of 1 compilation unit? Or would the foo.c be one complete compilation unit without the foo.h? – ant2009 Feb 16 '10 at 04:40
  • 91
    @robUK: the compiler doesn't even know about the .h files - these are combined into the .c files in the pre-processor. So yes you can say that the .c file, with all the headers included into it, are a single compilation unit. – Eli Bendersky Feb 16 '10 at 04:44
  • 1
    So does "static function" and "private function" means the same thing ? Similarly are "static global variables" and "private global variables" the same thing ? – user1599964 Jan 20 '13 at 08:58
  • 2
    @user1599964: there's no concept of "private" in C, per se. However, when functions and variables are made static in a C file, they are essentially private to this C file since they can't be accessed directly from other C files. – Eli Bendersky Jan 20 '13 at 13:27
  • I appreciate you're trying to clarify things, but your notion of compilers versus pre-processors is dated and confusing... modern "compilers" (as the word is generally used) internalise the preprocessor. It's accurate and simple enough to describe a translation or compilation unit as typically consisting of one .c implementation file and whatever headers it directly or indirectly `#include`s, and not bring preprocessor/compiler into it at all. – Tony Delroy Dec 16 '13 at 02:04
  • 11
    @TonyD maybe it is confusing, but it is how the compilation works. It may typically be one `.c` and bunch of header files, but the devil is always in what is *not* typical. – peterph Feb 28 '14 at 12:00
  • 3
    @peterph: then that can be addressed by saying "a translation unit consists of the source file(s) specified to the compiler on the command line, with each #include (direct or indirect) expanded in place". My point remains that describing "translation unit" adequately is less misleading or confusing than making statements like "A compilation unit is a single file the compiler sees." when there's not necessarily any single amalgamated "file" (on the disk, or even in the compiler's memory for that matter) involved. "static ... is "seen" only in the file it's declared in" - also misleading. – Tony Delroy Feb 28 '14 at 12:13
  • 9
    @TonyD Sorry, but you're wrong. Preprocessing and compilation are totally different steps, and it's crucial to know how they differ. – Miles Rout Apr 10 '14 at 07:26
  • 1
    @MilesRout: Even sorrier that you're wrong about me being wrong - I agree with the rest of what you've said, but it doesn't relate to or contradict what I've said. Eli: *"the compiler doesn't even know about the .h files - these are combined into the .c files in the pre-processor."*, then me *"modern "compilers" (as the word is generally used) internalise the preprocessor"*. I've talked about compil*er* not compil*ation*. – Tony Delroy Apr 10 '14 at 07:44
  • 11
    @TonyD The compiler does compilation. The preprocessor does preprocessing. Calling the toolchain 'the compiler' doesn't change what it is or what it does. – Miles Rout Apr 10 '14 at 09:23
  • 2
    Regarding the static function part, there is a good Q&A already: [static function in C](http://stackoverflow.com/q/5319361/2157640) – Palec Feb 06 '15 at 13:35
  • 1
    Might a functional definition to translation unit simply be the single .c file and all its direct/indirect includes which altogether produce a single .o file? – Bondolin Apr 28 '15 at 12:20
  • 2
    Why the same keyword is used in different senses? Once for storage type and other for limiting variable scope. They could not get other keywords!! C is unnecessarily made complex to understand by newbies. – Jon Wheelock Apr 08 '16 at 09:44
  • The two cases (1) and (2) are actually the same. It doesn't matter whether the "static int sa=10;" is "inside the function" or "outside the function". The compiled program is exactly the same regardless... – hft Sep 04 '16 at 20:13
  • @hft Wrong. For (1) `sa` is "seen" only inside the `foo()` function, whereas for (2) `sa` can be seen directly from `main()` or any other function in the same .c file. – Bludzee Nov 22 '16 at 13:31
  • In the example given it doesn't matter. compile it both ways and see for yourself. – hft Nov 22 '16 at 22:04
  • 1
    As someone who has never used `static` in anything other than OO fashion, this helped me understand the use of `state` in Perl too – Honinbo Shusaku Dec 12 '16 at 17:13
  • So when someone declares a global variable as static does that mean it can only be read by the file itself? Or do other files within the same directory also have access? – DevReacc Dec 13 '17 at 16:51
  • 2
    @paxdiablo If you were truly pedantic, you would refer to it as `translation unit` ;) – Kostas Jun 22 '18 at 14:00
  • @Palec Nope, your mentioned question has been posted years after this question. – harper Oct 11 '18 at 04:49
  • IMHO the term "static global" is completely misplaced. A variable or function can't be local to a specific file *and* global (visible throughout the whole program) at the same time. We say "static global" because we mean a variable declared at *global scope* (outside of any function) inside a file, but technically it isn't real *global*. It is lets call it "regional" to keep the difference to "local" in the manner of function-local. – RobertS supports Monica Cellio Jun 16 '20 at 22:32
  • Because of this ambiguity there is much confusion brought to people who come newly to C. One good example is a recent question, where the OP used the term "*static global*" and confused him/herself as well as the answerers, [here](https://stackoverflow.com/questions/62393585/creating-a-static-global-variable-length-2d-array). You can get a short overview in the comments to that question. – RobertS supports Monica Cellio Jun 17 '20 at 07:21
  • @EliBendersky Since your answer is viewed by many new C programmers I would highly suggest you to replace the term "*static global*". It is ambiguous, formally incorrect and confuses people. – RobertS supports Monica Cellio Jun 17 '20 at 07:24
  • 2
    The Wikipedia terminology is crap^Wwrong and should be removed. `static` does not "set scope" (scope is determined by the placement of a declaration inside or outside blocks). `static` sets the *linkage* of an identifier to *internal linkage* which means identifiers from other translation units cannot refer to it. This makes it possible to have a different object with the same name in another source file. – Jens Oct 09 '20 at 11:41
  • 1
    Fun trivia about why these two unrelated usages of static (storage duration, and linkage) got the same name. When the second one was introduced (I don't remember which one came first, probably the storage duration), the implementers of the new feature wanted old compilers to still be able to compile newer code. Introducing a new keyword (`intern` would have been wonderful) would have confused older compiler versions, and so they reused a keyword that existed. Globals already had the program long storage duration, so it became `static` for internal linkage as well. – Gauthier Sep 22 '22 at 21:47
  • So its like it only declares the static variables one and then subsequent calls of the function ignore its redefinition and use the value it was assigned on the original call, meanwhile it is also being incremented. It's keeping the variable within scope outside the scope of the function. – Ryan Mckenna May 17 '23 at 00:32
287

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.

Community
  • 1
  • 1
dreamlax
  • 93,976
  • 29
  • 161
  • 209
  • 5
    I didn't think C had array arguments? Linus Torvalds rants angrily about people doing this. – suprjami Sep 29 '15 at 11:02
  • 22
    @jamieb: C doesn't have array arguments, but this specific syntax means that the function expects `arg[0]` through to `arg[9]` to have values (which also implies that the function does not accept a null pointer). Compilers could utilise this information somehow for optimisation, and static analysers can utilise this information to ensure that the function is never given a null pointer (or if it can tell, an array with fewer elements than specified). – dreamlax Sep 29 '15 at 21:16
  • 26
    @Qix -- This was a new overloaded meaning given to `static` in C99. It is more than a decade and a half old, but not all compiler writers have embraced all of C99 features -- so C99 as a whole largely remains unknown. – Happy Green Kid Naps Dec 22 '15 at 16:42
  • 1
    @suprjami I'm not 100% sure what you mean by *"array arguments"*, but if you mean `int arr[n];`, then that is a *VLA (variable-length array)*, which was added in C99. Is that what you meant? – RastaJedi May 01 '16 at 04:58
  • Does it mean, I can not pass any char* to this function, because nobody knows if it could be incremented by 10 ... I doubt your answer, although its interesting. – Nikolai Ehrhardt Mar 20 '22 at 12:00
203

Short answer ... it depends.

  1. Static defined local variables do not lose their value between function calls. In other words they are global variables, but scoped to the local function they are defined in.

  2. Static global variables are not visible outside of the C file they are defined in.

  3. Static functions are not visible outside of the C file they are defined in.

Samuel Edwin Ward
  • 6,526
  • 3
  • 34
  • 62
cmcginty
  • 113,384
  • 42
  • 163
  • 163
  • 10
    So does "static function" and "private function" means the same thing ? Similarly are "static global variables" and "private global variables" the same thing ? – user1599964 Jan 20 '13 at 08:56
  • 47
    This is about C. There is no private/public in C. – chris Feb 14 '13 at 07:34
  • 32
    @user1599964 although there is no `private` in C, your analogy is good: static makes things "private" to a given file. And files in C often map to classes in C++. – Ciro Santilli OurBigBook.com Apr 23 '15 at 15:02
85

Multi-file variable scope example

Here I illustrate how static affects the scope of function definitions across multiple files.

a.c

#include <stdio.h>

/*
Undefined behavior: already defined in main.
Binutils 2.24 gives an error and refuses to link.
https://stackoverflow.com/questions/27667277/why-does-borland-compile-with-multiple-definitions-of-same-object-in-different-c
*/
/*int i = 0;*/

/* Works in GCC as an extension: https://stackoverflow.com/a/3692486/895245 */
/*int i;*/

/* OK: extern. Will use the one in main. */
extern int i;

/* OK: only visible to this file. */
static int si = 0;

void a() {
    i++;
    si++;
    puts("a()");
    printf("i = %d\n", i);
    printf("si = %d\n", si);
    puts("");
}

main.c

#include <stdio.h>

int i = 0;
static int si = 0;

void a();    

void m() {
    i++;
    si++;
    puts("m()");
    printf("i = %d\n", i);
    printf("si = %d\n", si);
    puts("");
}

int main() {
    m();
    m();
    a();
    a();
    return 0;
}

GitHub upstream.

Compile and run:

gcc -c a.c -o a.o
gcc -c main.c -o main.o
gcc -o main main.o a.o

Output:

m()
i = 1
si = 1

m()
i = 2
si = 2

a()
i = 3
si = 1

a()
i = 4
si = 2

Interpretation

  • there are two separate variables for si, one for each file
  • there is a single shared variable for i

As usual, the smaller the scope, the better, so always declare variables static if you can.

In C programming, files are often used to represent "classes", and static variables represent private static members of the class.

What standards say about it

C99 N1256 draft 6.7.1 "Storage-class specifiers" says that static is a "storage-class specifier".

6.2.2/3 "Linkages of identifiers" says static implies internal linkage:

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 6.2.2/2 says that internal linkage behaves like in our example:

In the set of translation units and libraries that constitutes an entire program, each declaration of a particular identifier with external linkage denotes the same object or function. Within one translation unit, each declaration of an identifier with internal linkage denotes the same object or function.

where "translation unit is a source file after preprocessing.

How GCC implements it for ELF (Linux)?

With the STB_LOCAL binding.

If we compile:

int i = 0;
static int si = 0;

and disassemble the symbol table with:

readelf -s main.o

the output contains:

Num:    Value          Size Type    Bind   Vis      Ndx Name
  5: 0000000000000004     4 OBJECT  LOCAL  DEFAULT    4 si
 10: 0000000000000000     4 OBJECT  GLOBAL DEFAULT    4 i

so the binding is the only significant difference between them. Value is just their offset into the .bss section, so we expect it to differ.

STB_LOCAL is documented on the ELF spec at http://www.sco.com/developers/gabi/2003-12-17/ch4.symtab.html:

STB_LOCAL Local symbols are not visible outside the object file containing their definition. Local symbols of the same name may exist in multiple files without interfering with each other

which makes it a perfect choice to represent static.

Variables without static are STB_GLOBAL, and the spec says:

When the link editor combines several relocatable object files, it does not allow multiple definitions of STB_GLOBAL symbols with the same name.

which is coherent with the link errors on multiple non static definitions.

If we crank up the optimization with -O3, the si symbol is removed entirely from the symbol table: it cannot be used from outside anyways. TODO why keep static variables on the symbol table at all when there is no optimization? Can they be used for anything? Maybe for debugging.

See also

C++ anonymous namespaces

In C++, you might want to use anonymous namespaces instead of static, which achieves a similar effect, but further hides type definitions: Unnamed/anonymous namespaces vs. static functions

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
41

It depends:

int foo()
{
   static int x;
   return ++x;
}

The function would return 1, 2, 3, etc. --- the variable is not on the stack.

a.c:

static int foo()
{
}

It means that this function has scope only in this file. So a.c and b.c can have different foo()s, and foo is not exposed to shared objects. So if you defined foo in a.c you couldn't access it from b.c or from any other places.

In most C libraries all "private" functions are static and most "public" are not.

Community
  • 1
  • 1
Artyom
  • 31,019
  • 21
  • 127
  • 215
  • 20
    +1 for mentioning x not on stack or heap. It's on the static memory space. – RoundPi Nov 05 '12 at 11:51
  • 1
    @Gob00st static memory space? you meant "Data Segment"...? – Yousha Aleayoub Mar 12 '18 at 10:12
  • @YoushaAleayoub See [this](https://en.wikipedia.org/wiki/.bss) and [this](https://en.wikipedia.org/wiki/Data_segment#BSS). – Ekrem Dinçel Nov 10 '20 at 18:08
  • `In most C libraries all "private" functions are static and most "public" are not.` Hello I have a question about this, you said `most` , I wonder how can `static` functions behave as public – Sekomer Dec 21 '20 at 12:06
  • 1
    @Sekomer • if a static function pointer "escapes" as a function pointer return value of another function, or by being set as a function pointer via member variable in a struct. – Eljay Dec 23 '20 at 17:05
30

People keep saying that 'static' in C has two meanings. I offer an alternate way of viewing it that gives it a single meaning:

  • Applying 'static' to an item forces that item to have two properties: (a) It is not visible outside the current scope; (b) It is persistent.

The reason it seems to have two meanings is that, in C, every item to which 'static' may be applied already has one of these two properties, so it seems as if that particular usage only involves the other.

For example, consider variables. Variables declared outside of functions already have persistence (in the data segment), so applying 'static' can only make them not visible outside the current scope (compilation unit). Contrariwise, variables declared inside of functions already have non-visibility outside the current scope (function), so applying 'static' can only make them persistent.

Applying 'static' to functions is just like applying it to global variables - code is necessarily persistent (at least within the language), so only visibility can be altered.

NOTE: These comments only apply to C. In C++, applying 'static' to class methods is truly giving the keyword a different meaning. Similarly for the C99 array-argument extension.

PMar
  • 301
  • 3
  • 2
  • 1
    Your (a) is redundant at best. No variable whatsoever is visible outside its scope. That's simply the definition of scope. What you mean is called *linkage* in the C Standard. `static` gives *internal linkage* to an identifier. – Jens Jul 09 '19 at 10:09
19

static means different things in different contexts.

  1. You can declare a static variable in a C function. This variable is only visible in the function however it behaves like a global in that it is only initialized once and it retains its value. In this example, everytime you call foo() it will print an increasing number. The static variable is initialized only once.

    void foo ()
    {
    static int i = 0;
    printf("%d", i); i++
    }
    
  2. Another use of static is when you implement a function or global variable in a .c file but don't want its symbol to be visible outside of the .obj generated by the file. e.g.

    static void foo() { ... }
    
Jason Plank
  • 2,336
  • 5
  • 31
  • 40
m-sharp
  • 16,443
  • 1
  • 26
  • 26
18

From 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.

OscarRyz
  • 196,001
  • 113
  • 385
  • 569
  • Wikipedia at its worst. Static sets linkage, not scope. Understanding the difference is crucial. – Jens Oct 09 '20 at 16:20
  • 4
    @Jens No one asking a question about `static` will know what `linkage` means. However, the concept of scope is common to practically all languages, so anyone should be able to roughly understand how `static` affects objects based on this description. For the same reason, it mentions "the containing file" rather than "the current compilation unit". – natiiix Jan 02 '21 at 02:36
  • @natiiix Linkage is not scope. `static` does not set scope. Even "the containing file" is wrong, since scope only starts at the end of a declarator, not at the beginning of a file. The Wikipedia entry as quoted is so misleading, it would make Trump blush. – Jens Jan 02 '21 at 09:43
  • 2
    @Jens It doesn't really matter though, at all. For all intents and purposes, `static` makes global variables local to the file and removes them from the truly global scope. There's no point flexing fancy terms when a simple question expecting a simple, straight-forward answer is asked. Sure, it's not exactly correct, but it helps everyone understand the general idea and that's more important than some terminology nuances. – natiiix Jan 02 '21 at 12:44
11

I hate to answer an old question, but I don't think anybody has mentioned how K&R explain it in section A4.1 of "The C Programming Language".

In short, the word static is used with two meanings:

  1. Static is one of the two storage classes (the other being automatic). A static object keeps its value between invocations. The objects declared outside all blocks are always static and cannot be made automatic.
  2. But, when the static keyword (big emphasis on it being used in code as a keyword) is used with a declaration, it gives that object internal linkage so it can only be used within that translation unit. But if the keyword is used in a function, it changes the storage class of the object (the object would only be visible within that function anyway). 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.
jigglypuff
  • 507
  • 1
  • 7
  • 20
  • There's a third storage class, *register*. Some people also make the case for a fourth storage class, *allocated*, for the storage returned by malloc and friends. – Jens Jun 01 '18 at 07:47
  • @Jens 'register' is only a hint to the compiler; register storage cannot be enforced from within the C source. So I wouldn't consider it a storage class. – GermanNerd Jul 16 '19 at 11:40
  • 2
    @GermanNerd I'm afraid the ISO C Standard disagrees with your view, as it clearly makes `register` a *storage-class specifier* (C99 6.7.1 Storage-class specifiers). And it is more than just a hint, for example you can't apply the address-of operator `&` on an object with storage class `register` regardless of whether the compiler allocates a register or not. – Jens Jul 16 '19 at 21:52
  • @Jens Thanks for reminding me about &. I might have done too much C++.....Anyhow, while 'register' is a storage-class specifier, in reality the compiler will likely create the same machine code for the (useless) 'auto' specifier as for the 'register' specifier. So the only thing remaining is the source-code level restriction of not being able to take an address. BTW, this little discussion led me to find a bug in Netbeans; since my latest update, it defaults to the g++ tool chain on new C projects! – GermanNerd Jul 17 '19 at 10:28
11

If you declare a variable in a function static, its value will not be stored on the function call stack and will still be available when you call the function again.

If you declare a global variable static, its scope will be restricted to within the file in which you declared it. This is slightly safer than a regular global which can be read and modified throughout your entire program.

Jonathan Adelson
  • 3,275
  • 5
  • 29
  • 39
7

Share what I learned about this point.

In C static is a declaration specifier, which falls into three categories:

  • storage classes: there are four classes: auto, static, extern and register.
  • type qualifiers: like keywords: const, volatile, etc.
  • type specifiers: like keywords: void, char, short, int, etc.

So static is a storage classes. It will determine the following three properties of each variable in a C program.

  • storage duration: means when memory is allocated for the variable and when the memory is released. A variable with static storage duration stays at the same memory location as long as the program is running.
  • scope: means the portion of the program text in which the variable can be accessed. A static variable has a file scope instead of a block scope.
  • linkage: means the extent to which the variable can be shared by different parts(or files) of a program. If a static variable is declared inside a block then it has no linkage. If a static variable is declared outside blocks, then it has internal linkage. Internal linkage makes it accessible in a single file.

The static storage class has a different effect on a variable depending on it is declared outside a block or inside a block. Need to consider case by case.

Chris Bao
  • 2,418
  • 8
  • 35
  • 62
6

A static variable is a special variable that you can use in a function, and it saves the data between calls, and it does not delete it between calls. For example:

void func(void) {
    static int count; // If you don't declare its value, it is initialized with zero
    printf("%d, ", count);
    ++count;
}

int main(void) {
    while(true) {
        func();
    }
    return 0;
}

The output:

0, 1, 2, 3, 4, 5, ...

Jens
  • 69,818
  • 15
  • 125
  • 179
Yagel
  • 1,184
  • 2
  • 18
  • 41
5

In C, static has two meanings, depending on scope of its use. In the global scope, when an object is declared at the file level, it means that that object is only visible within that file.

At any other scope it declares an object that will retain its value between the different times that the particular scope is entered. For example, if an int is delcared within a procedure:

void procedure(void)
{
   static int i = 0;

   i++;
}

the value of 'i' is initialized to zero on the first call to the procedure, and the value is retained each subsequent time the procedure is called. if 'i' were printed it would output a sequence of 0, 1, 2, 3, ...

schot
  • 10,958
  • 2
  • 46
  • 71
5

If you declare this in a mytest.c file:

static int my_variable;

Then this variable can only be seen from this file. The variable cannot be exported anywhere else.

If you declare inside a function the value of the variable will keep its value each time the function is called.

A static function cannot be exported from outside the file. So in a *.c file, you are hiding the functions and the variables if you declare them static.

Felipe Augusto
  • 7,733
  • 10
  • 39
  • 73
ant2009
  • 27,094
  • 154
  • 411
  • 609
4

It is important to note that static variables in functions get initialized at the first entry into that function and persist even after their call has been finished; in case of recursive functions the static variable gets initialized only once and persists as well over all recursive calls and even after the call of the function has been finished.

If the variable has been created outside a function, it means that the programmer is only able to use the variable in the source-file the variable has been declared.

Starhowl
  • 434
  • 5
  • 14
4

Static variables in C have the lifetime of the program.

If defined in a function, they have local scope, i.e. they can be accessed only inside those functions. The value of static variables is preserved between function calls.

For example:

void function()
{
    static int var = 1;
    var++;
    printf("%d", var);
}

int main()
{
    function(); // Call 1
    function(); // Call 2
}

In the above program, var is stored in the data segment. Its lifetime is the whole C program.

After function call 1, var becomes 2. After function call 2, var becomes 3.

The value of var is not destroyed between functions calls.

If var had between non static and local variable, it would be stored in the stack segment in the C program. Since the stack frame of the function is destroyed after the function returns, the value of var is also destroyed.

Initialized static variables are stored in the data segment of the C program whereas uninitialized ones are stored in the BSS segment.

Another information about static: If a variable is global and static, it has the life time of the C program, but it has file scope. It is visible only in that file.

To try this:

file1.c

static int x;

int main()
{
    printf("Accessing in same file%d", x):
}

file2.c

    extern int x;
    func()
    {
        printf("accessing in different file %d",x); // Not allowed, x has the file scope of file1.c
    }

run gcc -c file1.c

gcc -c file2.c

Now try to link them using:

gcc -o output file1.o file2.o

It would give a linker error as x has the file scope of file1.c and the linker would not be able to resolve the reference to variable x used in file2.c.

References:

  1. http://en.wikipedia.org/wiki/Translation_unit_(programming)
  2. http://en.wikipedia.org/wiki/Call_stack
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • I understand that the data is persistent, meaning that it won't be lost after each function call, but why doesn't `static int var = 1;` change the value back to one each time – Eames Nov 07 '17 at 23:00
1

A static variable value persists between different function calls andits scope is limited to the local block a static var always initializes with value 0

Jonathon
  • 49
  • 1
  • 12
1

There are 2 cases:

(1) Local variables declared static: Allocated in data segment instead of stack. Its value retains when you call the function again.

(2) Global variables or functions declared static: Invisible outside compilation unit (i.e. are local symbols in symbol table during linking).

Jonny Kong
  • 197
  • 1
  • 6
0

Static variables have a property of preserving their value even after they are out of their scope!Hence, static variables preserve their previous value in their previous scope and are not initialized again in the new scope.

Look at this for example - A static int variable remains in memory while the program is running. A normal or auto variable is destroyed when a function call where the variable was declared is over.

#include<stdio.h> 
int fun() 
{ 
  static int count = 0; 
  count++; 
  return count; 
} 

int main() 
{ 
  printf("%d ", fun()); 
  printf("%d ", fun()); 
  return 0; 
}

This will output: 1 2

As 1 stays in the memory as it was declared static

Static variables (like global variables) are initialized as 0 if not initialized explicitly. For example in the below program, value of x is printed as 0, while value of y is something garbage. See this for more details.

#include <stdio.h> 
int main() 
{ 
    static int x; 
    int y; 
    printf("%d \n %d", x, y); 
}

This will output : 0 [some_garbage_value]

These are the major ones I found that weren't explained above for a newbie!

era5tone
  • 579
  • 5
  • 14
0

The scope of static variables is limited to the file in which they are declared. This applies to static functions as well.

The scope of static variables declared in a function is different however. It is limited to the function, like non-static variables, but it retains its value across multiple calls to that function.

desertnaut
  • 57,590
  • 26
  • 140
  • 166
-4

In C programming, static is a reserved keyword which controls both lifetime as well as visibility. If we declare a variable as static inside a function then it will only visible throughout that function. In this usage, this static variable's lifetime will start when a function call and it will destroy after the execution of that function. you can see the following example:

#include<stdio.h> 
int counterFunction() 
{ 
  static int count = 0; 
  count++; 
  return count; 
} 

int main() 
{ 
  printf("First Counter Output = %d\n", counterFunction()); 
  printf("Second Counter Output = %d ", counterFunction()); 
  return 0; 
}

Above program will give us this Output:

First Counter Output = 1 
Second Counter Output = 1 

Because as soon as we call the function it will initialize the count = 0. And while we execute the counterFunction it will destroy the count variable.

Chris Tang
  • 567
  • 7
  • 18
Makdia Hussain
  • 744
  • 3
  • 11
  • 4
    >Above program will give us this Output: First Counter Output = 1 Second Counter Output = 1 < Not true. Static variables get initialized only once. So the output will be 1, then 2, and so on. – GermanNerd Jul 16 '19 at 11:25
  • 1
    Global and Static variables are initialized to `0`, You shouldn't re-assign them to zero in every function call. – Sekomer Dec 21 '20 at 12:11