Code:

double call_by_name(const char *name, int arg) { static const char *names[] = {"sin", "cos", "tan", NULL}; static double (*fp[])(double) = {sin, cos, tan}; for (int i = 0; names[i] != NULL; i++) if (strcmp(names[i], name) == 0) return ((*fp[i])(arg)); return 0; } 

Why are arrays *names[] and *fp[] have the keyword static ? What is it for in this context?

    1 answer 1

    Local static objects are initialized when the function is first called and exist until the end of the program's life (although it is available only inside the function). Declaration as static in this case eliminates the creation and initialization of arrays with each function call. Those. With multiple function calls, you can save on the initialization procedure, but at the same time we lose in the memory used.

    Example 褋++ :

     #include <stdio.h> int g() { printf("g\n"); return 42; } void f() { static int i = g(); } int main() { f(); f(); f(); } 

    g will be executed only once.

    But for c this code is not collected at all, because c requires to compile static constants for initialization of static objects.

    • one
      But if I call this function only 1 time while the program is running, does the speed only decrease? After all, in this case, some memory area will be occupied and it will 'hang' until the end of the program? - Chebakov Dmitry
    • one
      @ Chebakov Dmitry static variables are placed in a special memory area just below the constants. The speed does not affect, but like any sington it is actually a leak, calculated at the stage of architecture. - pavel
    • 3
      @ Chebakov Dmitry, by the way, static outside a function, for example for a global variable, has a slightly different meaning. - Vladimir Gamalyan
    • one
      @VladimirGamalian static has a lot of meanings depending on the context: local, global, class members (functions, data). - 伪位蔚蠂慰位蠀蟿
    • one
      @ ChebakovDmitry, you can consider static variables as global, but with limited scope. Their main property is the preservation of the value between function calls, in contrast to local functions that are located on the stack and therefore exist only during the activity of the function where they are defined. - avp