gpt4 book ai didi

c - 某些脚本语言的算术运算

转载 作者:行者123 更新时间:2023-12-03 20:55:06 24 4
gpt4 key购买 nike

我正在研究某种脚本语言。包含结构的值是

struct myvar
{
char name[NAMELEN];
int type;
void* value;
}
type = 0 --> int* value
type = 1 --> char* value
type = 2 --> float* value

我在算术运算方面遇到了一些问题。似乎我需要对每个操作进行各种类型转换,这发展成为为每个操作编写一大堆代码,如:

case 0:  // "="
if(factor1.name)
{
if((factor1.type == 1) && (factor2.type==1))
{
free(factor1.value);
int len = (strlen((STRING)factor2.value)+1)*sizeof(char);
factor1.value = malloc(len);
memcpy(factor1.value,factor2.value,len);
}
else if((factor1.type == 2) && (factor2.type==2))
*(FLOAT*)factor1.value = *(FLOAT*)factor2.value;
else if((factor1.type == 0) && (factor2.type==0))
*(INTEGER*)factor1.value = *(INTEGER*)factor2.value;
else if((factor1.type == 0) && (factor2.type==2))
*(INTEGER*)factor1.value = *(FLOAT*)factor2.value;
else if((factor1.type == 2) && (factor2.type==0))
*(FLOAT*)factor1.value = *(INTEGER*)factor2.value;
else
GetNextWord("error");
}
break;

有什么方法可以避免这个烦人的过程吗?否则我别无选择,只能为每个 "=","~","+","-","*","/","%",">","复制粘贴这段代码<",">=","<=","==","~=","AND","OR"

最佳答案

对值使用union 而不是struct:

struct myvar {
enum {
STRING, INT, FLOAT,
} type;

union {
char strval[NAMELEN];
int intval;
float fltval;
} val;
};

然后在您的脚本语言中执行赋值运算符时,您只需执行以下操作:

factor1 = factor2;

要根据您要执行的类型获取正确的值:

switch (operand.type) {
case STRING:
printf("%s", operand.val.strval);
break;

case INT:
printf("%d", operand.val.intval);
break;

case FLOAT:
printf("%f", operand.val.fltval);
break;
}

关于c - 某些脚本语言的算术运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6698379/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com