【问题标题】:Alternative declarations of a variable depending on an if condition取决于 if 条件的变量的替代声明
【发布时间】:2017-10-30 16:57:26
【问题描述】:

我想要 as,如果 i 为 1,则为 int 类型,否则为 char 类型,但是当我编译此代码时,会遇到以下错误:

> 1.c: In function ‘main’:
> 1.c:18:16: error: ‘a’ undeclared (first use in this function)
>              if(a)
>                 ^
> 1.c:18:16: note: each undeclared identifier is reported only once for each function it appears in



  #include <stdio.h>
    #define macro
    void main()
    {
        int i=1;
    #ifdef macro
        if (i==1)
        {
            int a;
        }
        else
    #endif
        {
            char a;
        }
        if(a)
        {
        printf("INDOE ");
        }
    }

【问题讨论】:

  • 变量有一个声明它们的块的范围。
  • 您可以将a 声明为int,然后在必要时有条件地将其转换为char
  • 你想用 a 做什么?
  • 如果这是 C++,您将使用模板(假设 i 的值在编译时已知)。
  • rohit 你熟悉union吗?

标签: c if-statement variable-declaration


【解决方案1】:

我想要 as,如果 i 为 1,则 a 为 int 类型,否则为 char 类型

到此为止,编译后的 C 代码不知道类型,因此您无法在运行时设置类型——在您编译程序时它已经“硬编码”了。

旁注:

    {
        char a;
    }
    if(a)

大括号给变量一个作用域,所以在右大括号之后,a 不再存在。


有很多方法可以解决这个问题,它们都涉及到您存储自己的类型信息。粗略的想法:

enum mytype { MT_INT, MT_CHAR };

struct myvalue {
    enum mytype type;
    union {
        int a_int;
        char a_char;
    };
};


[...]

struct myvalue x;
// [...]
if (i==1) x.type = MT_INT;
else x.type = MT_CHAR;
// [...]

然后在x.a_intx.a_char的每个访问中,先检查x.type,就知道访问哪个成员了。

【讨论】:

  • "can't set a type at runtime" --> VLA 允许有限的运行时类型变化——数组大小。
  • @chux 虽然这显然是正确的,但我想不出一种将它整合到我的答案中的方法(不会过多地分散实际的注意力)——有什么建议吗?
  • 这只是对您的好答案的一个说明。
【解决方案2】:

C 中变量的范围仅限于您声明它的块。 int a 仅在 if 中可用。并且 char a 仅在 else 中可用

【讨论】:

    【解决方案3】:

    搜索“范围”概念。在 C 语言中,在一个范围内定义的变量将无法在其外部或在上面的范围内访问,但可以在下面的范围内访问。

    【讨论】:

      【解决方案4】:

      看起来你希望你的条件由预处理器处理。例如。

       #include <stdio.h>
      
      #define i 1
      
      #if i
      #define ATYPE int
      #else
      #define ATYPE char
      #endif
      int main(int argc, char* args)
          {
              ATYPE a;
              printf("%d\n", sizeof(a));
          }
      

      我当然不会推荐#define'ing i,但这看起来有点像你想要做的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-04-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-06
        • 1970-01-01
        相关资源
        最近更新 更多