我如何改变一个类型的变量到另一个用C? [英] How I change a variable of a type to another one in C?

查看:109
本文介绍了我如何改变一个类型的变量到另一个用C?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要做到这一点:

int main () {
  bla bla bla

  void *onetype;

  switch (USER_INPUT_TYPE) {

      CASE CONVERT_TO_CHAR:
          convert onetype VOID TO CHAR >>> HOW???

      CASE CONVERT_TO_INT:
          convert onetype VOID TO INT >>> HOW???

   LOT OF CASES...
   }
}

是的,我知道的类型转换,但是类型转换是一个临时的变化。

Yes, I know type casting, but type casting is a 'temporary' change.

那么,有没有办法做到在C?

So, is there any way to accomplish it in C?

编辑:

罢罢罢!请看看,你在做什么是类型转换,我知道这一点,你所创建的理想类型如int i =(int)的onetype,我不想这样的另一个变量,我想别的东西一样onetype =(INT )onetype,无需重新创建它们,没有分配另一个变量。

Stop stop stop! Please, see, what are you doing is type casting, I KNOW THIS, you are creating another variable of the desirable type like int i = (int) onetype, I don't want this, I want something else like onetype = (int) onetype, without recreate them, without allocate another variable.

非常感谢你们!

推荐答案

你想要的是运行时类型信息 - 有一个变量,其类型是唯一在运行时确定的。 C没有在语言这个功能 - 一旦程序被编译,类型被删除,只有内存斑点存在。动态语言保持类型信息和本地实现这一点。

What you want is run-time type information - to have a variable in which the type is only determinable at run time. C does NOT have this functionality in the language - once the program is compiled, types are erased, and only memory blobs exist. Dynamic languages maintain type information and implement this natively.

您可以设计自己的本土型标签系统:

You can devise your own home-grown type tagging system:

typedef union {
int i;
char c;
float f;
} evil;

typedef struct {
  evil value;
  int type;
} tagged_t;

enum {
  TYPE_INT, TYPE_CHAR, TYPE_FLOAT
};

tagged_t bar;
bar.value.c = 'a';
bar.type = TYPE_CHAR;

现在每次你想使用你的tagged_t类型的时候,你必须实现的条件为你存储每个可能的类型的变量,或类型是否被允许在code或不是该地区能够确定。

Now every time you wish to use your tagged_t type, you must implement a condition for each possible type of variable you are storing, or be able to determine whether a type is allowed in that area of code or not.

这篇关于我如何改变一个类型的变量到另一个用C?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆