5

How can I convert a string into a variable name? E.g. I have a list of strings:

     "str1", "str2", "str3", etc.

And a structure:

struct my_struct {  
       int str1;  
       int str2;  
       int str3;  
} m = {5, 10, 15, ... etc};  

Given a string "str2", I want to print the variable associated with that name m.str2. Does C have any way to do this?

Thank you!

2
  • There is no language-defined way to access m.str2 given m and the string "str2" unless you write it. The C language doesn't provide reflection native to the langauge.
    – WhozCraig
    Commented Aug 3, 2015 at 3:21
  • Thanks for the answer. I was trying to do the reverse of "Stringification", as the gcc manual shows: gcc.gnu.org/onlinedocs/cpp/Stringification.html. Commented Aug 3, 2015 at 3:30

7 Answers 7

10

This is simply not possible in C.
Check out this question for more details. How to return a variable name and assign the value of the variable returned in c

To quote Wichert, 'I suggest that you reconsider the problem you are trying to solve and check if there might not be a better method to approach it. Perhaps using an array, map or hash table might be an alternative approach that works for you.'

8

In C you cannot create variable or symbol names dynamically.

3

Here's one way.

if ( strcmp(str, "str2") == 0 )
{
   // Use m.str2
}

That will be a problem with hundreds of variables. You'll have to come up with some other mechanism in that case.

2
  • I have hundreds of variables, so this will not scale. Commented Aug 3, 2015 at 3:29
  • 1
    @user2511788 Use macros or generate some code using another program. You'll only have to do it once.
    – M.M
    Commented Aug 3, 2015 at 3:51
3

#define get_val(x) (m.str##x) seems to be the way to do just that - ## is a token-pasting operator, so to make use of this macro you just need to call the function it defines with the number in the string name as its parameter, get_val(2)

1

I will suggest a slightly simpler, albeit maybe not as efficient solution.

This was a solution I came up with for a project after consulting with one of my professors.

Essentially, strings are just ASCII characters, and C file containing variable names can be thought of in the same way.

Thus, suppose you have a list of strings that you would like to turn into variable names for integers.

First, define your structure in a header file that can be accessed by all files in your directory, for instance 'struct.h'.

The first step is to convert the string names to their respective integers

Simply create an empty header, called variable_names.h, include struct.h, and once and for all invoke the following loop in your main file:

const char *strings[] = {"str1", "str2", ... }
fp = fopen("variable_names.h", "a");
fprintf(fp, "#ifndef FILE1_H \n");
fprintf(fp, "#define FILE1_H \n");
fprintf(fp, "extern int* m_integers = {");
int i;
for(i = 0; i < sizeof(strings) - 1; i++){ fprintf(fp, "m.%s,", strings[i]);}
fprintf(fp, "m.%s } ", strings[i+1])
fprintf(fp, "#endif");

Now you have a linear mapping between the string name and value in your structure via the m_integers array. Next is to create some mapping that takes in the string name and points it to this integer. I will use UTHASH, but there are certainly other ways.

Thus, in your main file,

#include "uthash.h"
#include "variable_names.h"
...

struct opcode_table{
     char* opcode_key;
     int opcodes_val;
     UT_hash_handle hh;
 };
struct opcode_table *mapping = NULL;

struct opcode_table* s = NULL;
for (int i = 0; i  < opcode_size; i++){
  s = (struct opcode_table*) malloc(sizeof(*s)); 
  s->opcodes_key = strings[i]; // the string 
  s->opcode_val = m_integers[i]; // the integer
  HASH_ADD(hh,mapping, opcodes_key, sizeof(int),s);
}

^ Please go easy on the code, just a rough example of what could be done. I'm sure there are some mistakes, but high level I believe this should work.

As on overview, the idea is essentially, you wrote to an external file the ascii characters "m.string1", which once is written, is interpreted as an integer via the structure definition, yielding you your desired outcome. Now, you must simply look up the string in the hash table, and you get the integer in the structure.

Also, I would appreciate any feedback if someone finds a better way or this approach is flawed. Thanks!

0

Here is one way, please check the sample code I have written. I have used integer pointer ptr to do this.

#include <stdio.h>
#include <string.h>
const char *s[] = {"str1", "str2", "str3", "str4", "str5", "str6", "str7", "str8", "str9", "str10"};
struct temp
{
    int str1;
    int str2;
    int str3;
    int str4;
    int str5;
    int str6;
    int str7;
    int str8;
    int str9;
    int str10;
}m = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};

main()
{
    char str[10];
    int *ptr;
    int i;
    ptr = &m.str1;
    printf("enter string: \t");
    scanf("%s", str);
    for(i=0;i<10;i++)
    {
        if(strcmp(str,s[i]) == 0)
        {
            break;
        }
    }
    printf("value = %d\n", *(ptr+i));

}

Please correct me if any mistakes.

2
  • I wanted a way to avoid strcmp, hence checking if there was any pre-processor tricks Commented Aug 3, 2015 at 9:46
  • if you want to give strings in runtime then pre-processor tricks will not work.
    – venki
    Commented Aug 3, 2015 at 9:58
0

What you are wanting is what the Smalltalk Language had used in it's Interpreter in the 1980;s and what Python still uses to create Object Variables from string char's through a TTY Command Shell Program in C language.

We do these by using structs with a nested struct next. But the actual variable, names are never actually declared. They are however matched by a conditional search for their stored char name in a struct or if it does not exist it creates them.

If it does exist in the struct list it will conditionally find() it and its stored value or assign its value depending on what your program has it designed to do.

An example of this is understood best by the Token's being used for (tok),(s),(t),(e) and several others as look-aheads read in by a token stream:

if (tok == "IDENT";) {

When it finds a identifier(variable tag from lex) token as above it will look ahead and fetch the variable name, then either create it, perform a calculation of its look-ahead contains another variable after another char type definition such as "CHAR" or "FLOAT"(for a double)etc.

What it does now is to set everything conditionally as it's being read into the struct list assigned by the tok token stream.

"CHAR" "x" "EQUALS" "INT" "5" "NEWL(for \N)" "CHAR" "y" "EQUALS" "INT" "5" "NEWL" "PRNT" "CHAR" "x" "NEWL".

So basically all variables through void functions are conditionally being assigned to a struct list and likewise having their values stored by them.

And it is not the variable you need to match its stored variable name. Its only the match it requires from a single tok variable and it's look-aheads that you need--

struct Var v; //--declared in .h then--
if(tok == 'CHAR') //--and-- 
v = {tok2, s, t} //

"tok2" being your vars char name and "s" and "t" being look-aheads to fetch, calculate and or assign them. Basically Python uses one C variable named tok to name them all. Then matches make them both dynamic and easy for Python to use them. atoi and strtod make integer and doublke conversion on the fly also. Its advanced stuff.

This whole process is called "Scanners" and "Calculators" in early ANCI C. Study Dennis Ritchie and Tobias Shrighner. Tobias worked on several Interpreters in fact.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.