User Tools

Site Tools


info:c_global_local

Variables in C

Static global variables

Test case: Code for c1.c:

#include <stdio.h>
 
static int stat;
 
int getSetStat1(int n) {
    int v = stat;
    stat = n;
    return v;
}
 
int main(void) {
    getSetStat2(4);
    getSetStat1(3);
    printf("stat.1=%i, stat.2=%i\n",stat, getSetStat2(5));
    return 0;
}

Code for c2.c:

static int stat;
 
int getSetStat2(int n) {
    int v = stat;
    stat = n;
    return v;
}

Compile with gcc c2.c c1.c. Output: stat.1=3, stat.2=4.

Keyword Static in functions

#include <stdio.h>
 
void f() {
    static int x;
    printf("%i\n", x);
    x = 5;
    return;
}
 
 
int main(void) {
    f();
    f();
    return 0;
}

The code prints

0
5
info/c_global_local.txt · Last modified: 2010/01/25 10:21 by moritz

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki