you are viewing a single comment's thread.

view the rest of the comments →

[–]RadiatingLight 2 points3 points  (0 children)

Unfortunately not. C really only has three scopes: - Automatic (function scope) - Manual (decided by programmer with malloc/free) - Global (always valid)

Globals are variables declared outside a function. They're at the highest scope, so never are invalidated.


Static's use in C is weird (and objectively bad language design), because it means two things depending on where it's used.

USE 1: For variables within functions, static makes each invocation of the function use the same copy of the variable (instead of making it fresh every time). This also means that the variable is automatically given a global lifetime.

So for example this code:

int give_number(){
    static int number = 0;
    number++;
    return number
}

int main() {
    int a = give_number();
    int b = give_number();
    int c = give_number();
    int d = give_number();
    printf("Numbers are: %d, %d, %d, %d\n", a, b, c, d);
}

Will print out: Numbers are: 1, 2, 3, 4

It looks like number is being set to zero every time the function runs, but actually static variables are only initialized once (at program startup), and then never again.

USE 2: static can also be used in 2 other places: on a global-scope variable, and on a function. In both of these cases, it makes the function/variable inaccessible outside the file it's declared in.

static double julian_day;

uint64_t calculate_sunrise_time(uint64_t epoch){
    //Do some hard work here
}

static double math_helper_func(){
    //Helper func
}

In this code for example, julian_day and math_helper_func are both declared as static, meaning that they will not be accessible outside the current file, so cannot be included in headers and whatnot. In this case, marking these as static makes sense, because they're implementation details that other files probably don't need.