简体   繁体   English

C中的动态变量声明

[英]Dynamic variable declaration in C

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.我是一名 ruby​​ 开发人员,自从我用 C 编码以来已经有很长时间了。我想在 C 中使用一种行为类似于符号的数据类型。

Is this possible?这可能吗?

  • Program asks user for name程序要求用户输入姓名

  • User replies - "foobar"用户回复——“foobar”

  • Program declares an integer with the same name ie程序声明了一个同名的整数,即

    int foobar;

Unlike in interpreted languages, C does not have a dictionary of variable names at runtime.与解释型语言不同,C 在运行时没有变量名字典。 There exist no variable names at runtime at all.运行时根本不存在变量名。 Hence unfortunately it is impossible to do what you want in C.因此不幸的是,不可能在 C 中做你想做的事。

如果不实现您自己的符号表来模拟所需的行为(本质上,实现您自己的微编程语言),就不可能在 C 中做到这一点。

No. C must know names at compile time.不。C 必须在编译时知道名称。

The best you could do is create your own dictionary of names and values.您能做的最好的事情就是创建自己的名称和值字典。 Much work though.虽然工作量很大。

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?您将使用或对您的 foobaf 变量执行什么样的操作?

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.正如其他人所建议的那样,您可以使用数据结构将用户名与一段整数数据动态关联,但知道您想用它做什么将有助于提供有关是否有必要以及您可能需要哪些数据结构和算法的建议看。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM