C program to get variable name as input and print value

前端 未结 4 888
一整个雨季
一整个雨季 2021-01-16 16:58

I have a program test.c

int global_var=10;
printf(\"Done\");

i did

gcc -g test.c -o test

My query is I

4条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-16 17:37

    No, C doesn't have introspection. Once the compiler has generated code, the program can not look up variable names.

    The way these things are usually solved is by having a collection of all special variables that needs to be looked up by name, containing both the actual name as a string and the variable it self.

    Usually it's an array of structures, something like

    struct
    {
        const char *name;
        int value;
    } variables[] = {
        { "global_var", 10 }
    };
    

    The program can then look through the array variables to search for "global_var" and use (or change) the value in the structure.

提交回复
热议问题