Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to declare a variable in C, the name of which is given by the user at runtime?

Tags:

c

variables

Is it possible to declare a variable in C, the name of which is given by the user at runtime? If yes, then how?

like image 468
Quixotic Avatar asked Aug 31 '12 16:08

Quixotic


People also ask

Can we declare a variable named Main in C?

The C standard says variable names should not match with standard C keywords and standard function names.

How do you declare a variable called a name?

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.

Can we declare variable anywhere in C?

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.


2 Answers

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.

like image 168
Sergey Kalinichenko Avatar answered Oct 21 '22 07:10

Sergey Kalinichenko


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.

like image 31
Avi Berger Avatar answered Oct 21 '22 07:10

Avi Berger