summaryrefslogtreecommitdiff
path: root/devdocs/c/language%2Fstatic_storage_duration.html
blob: 2ca1a227f394550d00dfd875e8d3683b03f97dcc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
    <h1 id="firstHeading" class="firstHeading">Static storage duration</h1>            <p>An object whose identifier is declared without the storage-class specifier <code>_Thread_local</code>, and either with external or internal <a href="storage_duration#Linkage" title="c/language/storage duration">linkage</a> or with the storage-class specifier <code>static</code>, 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.</p>
<h3 id="Notes"> Notes</h3> <p>Since its stored value is initialized only once, an object with static storage duration can profile the invocations of a function.</p>
<p>The other use of the keyword <code>static</code> is <a href="file_scope" title="c/language/file scope">file scope</a>.</p>
<h3 id="Example"> Example</h3> <div class="t-example"> <div class="c source-c"><pre data-language="c">#include &lt;stdio.h&gt;
 
void f (void)
{
    static int count = 0;   // static variable   
    int i = 0;              // automatic variable
    printf("%d %d\n", i++, count++);
}
 
int main(void)
{
    for (int ndx=0; ndx&lt;10; ++ndx)
        f();
}</pre></div> <p>Output:</p>
<div class="text source-text"><pre data-language="c">0 0
0 1
0 2
0 3
0 4
0 5
0 6
0 7
0 8
0 9</pre></div> </div>           <div class="_attribution">
  <p class="_attribution-p">
    &copy; cppreference.com<br>Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.<br>
    <a href="https://en.cppreference.com/w/c/language/static_storage_duration" class="_attribution-link">https://en.cppreference.com/w/c/language/static_storage_duration</a>
  </p>
</div>