繁体   English   中英

在 if 语句 C 中声明一个新变量

[英]Declare a new variable in if statement C

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

插入文件

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);

变量的作用域是声明它的块。 这意味着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]);

暂无
暂无

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

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