首页 > 解决方案 > 在 if 语句 C 中声明一个新变量

问题描述

我有一个 Insert函数,其中有一个char诸如参数。使用这个参数 ( type) 我决定了 pos 的类型。例如:如果我打电话 Insert('i'),我指定我必须使用一个 Int。问题是,如果我在 if 之外的每个 if 语句中声明一个新参数,它就看不到变量。就我而言,printf("%d", array[pos]);它告诉我pos没有初始化。我该如何解决?

插入.c

void insert(char type){
    if(type=='i'){
        int pos;
    }else if(type=='f' || type=='d'){
        double pos;
    }else if(type=='c'){
        char pos;
    }else if(type=='s'){
        char *pos;
    }else {
        int pos;
    }

    int array[2];
       //I put some values in the array.
    printf("%d", array[pos]);

主程序

int main(){
    char c = 'i';
    insert(c);

标签: arrayscfunctionvariablesparameters

解决方案


变量的范围是声明它的块。这意味着pos变量一到达右括号就会消失。该结构允许您对不同类型使用相同的名称,但 C 不允许您在声明它的块之外使用变量。

您在这里需要的是一个联合,并且为了能够正确使用它,我建议您将它与它的类型指示一起包含到一个结构中:

struct variant {
    enum {i, d, c, s} type;
    union {
        int i;
        double d;
        char c;
        char *s;
    };
};

然后你可以使用它:

void insert(char type){
    variant pos;
    if(type=='i'){
        pos.type = i;
    }else if(type=='f' || type=='d'){
        pos.type = f;
    }else if(type=='c'){
        pos.type = c;
    }else if(type=='s'){
        pos.type = s;
    }else {
        pos.type = i;
    }

    ...
    if (pos.type == i) {
        printf("%d", array[pos.i]);

推荐阅读