Is it possible to declare a variable in C, the name of which is given by the user at runtime? If yes, then how?
The C standard says variable names should not match with standard C keywords and standard function names.
To declare a variable is to create the variable. In Matlab, you declare a variable by simply writing its name and assigning it a value. (e.g., 'jims_age = 21;'). In C, Java you declare a variable by writing its TYPE followed by its name and assigning it a value.
Modern C compilers such as gcc and clang support the C99 and C11 standards, which allow you to declare a variable anywhere a statement could go. The variable's scope starts from the point of the declaration to the end of the block (next closing brace). You can also declare variables inside for loop initializers.
No, this is not possible: variable names do not survive the compilation step, becoming addresses and offsets "baked into" the compiled binary code.
It is, however, possible to declare a variable the name of which is given by the developer at compile-time by using a -D
or a comparable option of your C compiler.
As dasblinkenlight has correctly answered, no.
What you can do and might achieve your implementation goals, is to create and maintain at runtime your own dictionary of strings and associated values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With