4

I'm a ruby developer and its been long time since I've coded in C. I want to use a datatype in C which behaves like a symbol.

Is this possible?

  • Program asks user for name

  • User replies - "foobar"

  • Program declares an integer with the same name i.e.

    int foobar;
    
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Prakhar
  • 3,486
  • 17
  • 44
  • 61
  • 2
    I believe it is not possible because the identifiers for a type should be known at compilation phase in `C`. – Mahesh May 19 '11 at 21:07
  • 2
    C is not a dynamic language, and it's "low level" compared to Ruby. You'll need to adapt your thinking and programming idioms accordingly. – Paul R May 19 '11 at 21:08
  • 1
    You might be able to use a pointer variable for this purpose? int *var; var = (int *)malloc(sizeof(int)); while storing the name of variable in yet another array/variable. – Usman Saleem May 19 '11 at 21:08
  • 3
    This is a bad idea anyway even in languages that allow it. –  May 19 '11 at 21:09
  • "its been long" -- I'll bet! You're looking for an eval function, but all C code is compiled ... at compile time. – Jim Balter May 19 '11 at 23:15

4 Answers4

8

Unlike in interpreted languages, C does not have a dictionary of variable names at runtime. There exist no variable names at runtime at all. Hence unfortunately it is impossible to do what you want in C.

Hyperboreus
  • 822
  • 5
  • 4
  • 1
    However, nothing prevents you from building your own dictionary at runtime. C is probably not the best language for this, but it can be (and most likely has been) done. – Alexandre C. May 19 '11 at 21:16
  • @Alexandre C. Since numerous interpreters have been written in C, it has indeed been done, repeatedly. Actually, any C program having a hash table that maps strings to values does this. – Jim Balter May 19 '11 at 23:18
2

It's not possible to do this in C without implementing your own symbol table to emulate the desired behavior (essentially, implementing your own micro-programming language).

jwodder
  • 54,758
  • 12
  • 108
  • 124
1

No. C must know names at compile time.

The best you could do is create your own dictionary of names and values. Much work though.

Mouse Food
  • 231
  • 3
  • 9
  • It's not much work at all, given a hash table API such as in glib. Heck, even POSIX has hcreate/hsearch/hdestroy in search.h – Jim Balter May 19 '11 at 23:22
  • A bit of work from scratch, but it depends on what you define as much work. Libraries are good. – Mouse Food May 20 '11 at 14:01
0

What do you want to do with the username-as-variable once you have it? What kind of operations would you perform with or on your foobaf variable?

As others have suggested you could use a data structure to dynamically associate the user name with a piece of integer data but knowing what you want to do with it would help inform suggestions as to whether that's even necessary and which data structures and algorithms you might want to look at.

Derek
  • 3
  • 3