Dynamic variable declaration in C

狂风中的少年 提交于 2019-12-01 09:41:42

问题


I'm a ruby developer and its been long since I've coded in C. I have this small issue -Basically I want to use a datatype in C which behaves like a symbol in C.

In other words, is this possible in C?

  • Program asks user for name
  • user replies - "foobar"
  • declare an integer with the same name i.e.

    int foobar

Thanks


回答1:


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.




回答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).




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/6064873/dynamic-variable-declaration-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!