Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There are two separate concepts here:</p> <ul> <li><em>scope</em>, which determines where a name can be accessed, and</li> <li><em>storage duration</em>, which determines when a variable is created and destroyed.</li> </ul> <p><em>Local</em> variables (pedantically, variables with <em>block scope</em>) are only accessible within the block of code in which they are declared:</p> <pre><code>void f() { int i; i = 1; // OK: in scope } void g() { i = 2; // Error: not in scope } </code></pre> <p><em>Global</em> variables (pedantically, variables with <em>file scope</em> (in C) or <em>namespace scope</em> (in C++)) are accessible at any point after their declaration:</p> <pre><code>int i; void f() { i = 1; // OK: in scope } void g() { i = 2; // OK: still in scope } </code></pre> <p>(In C++, the situation is more complicated since namespaces can be closed and reopened, and scopes other than the current one can be accessed, and names can also have class scope. But that's getting very off-topic.)</p> <p><em>Automatic</em> variables (pedantically, variables with <em>automatic storage duration</em>) are local variables whose lifetime ends when execution leaves their scope, and are recreated when the scope is reentered.</p> <pre><code>for (int i = 0; i &lt; 5; ++i) { int n = 0; printf("%d ", ++n); // prints 1 1 1 1 1 - the previous value is lost } </code></pre> <p><em>Static</em> variables (pedantically, variables with <em>static storage duration</em>) have a lifetime that lasts until the end of the program. If they are local variables, then their value persists when execution leaves their scope.</p> <pre><code>for (int i = 0; i &lt; 5; ++i) { static int n = 0; printf("%d ", ++n); // prints 1 2 3 4 5 - the value persists } </code></pre> <p>Note that the <code>static</code> keyword has various meanings apart from static storage duration. On a global variable or function, it gives it <em>internal linkage</em> so that it's not accessible from other translation units; on a C++ class member, it means there's one instance per class rather than one per object. Also, in C++ the <code>auto</code> keyword no longer means automatic storage duration; it now means automatic type, deduced from the variable's initialiser.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload