【问题标题】:Declare a new variable in if statement C在 if 语句 C 中声明一个新变量
【发布时间】:2021-03-04 21:23:47
【问题描述】:

我有一个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]);

ma​​in.c

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

【问题讨论】:

  • 这不是 C 的工作方式,你不能只是“改变”变量的类型。所有这些声明都是完全独立的,这就是为什么它们都只存在于自己的范围内
  • 你不能这样做,但更重要的是你真正想要完成的事情。使用doublechar* 索引数组是否有意义?您能否解释一下您的想法或将代码扩展为不那么含糊?
  • 这看起来像一个典型的XY Problem

标签: arrays c function variables parameters


【解决方案1】:

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

【讨论】:

  • 如果这是针对 OP 特定用例的适当解决方案,是的。
猜你喜欢
  • 1970-01-01
  • 2018-11-07
  • 1970-01-01
  • 1970-01-01
  • 2013-07-09
  • 1970-01-01
  • 2014-04-12
  • 2014-08-26
  • 1970-01-01
相关资源
最近更新 更多