C - If 条件中的变量声明在 Else 中可用?

C - Variable Declaration in If Condition Available in Else?

如果我在 C 中的 if 条件中声明了一个变量,该变量是否也可用于 else 分支? 例如:

if((int x = 0)){
  foo();
} else{
  x++;
  bar(x);
}

找不到答案,至少不是我所说的那样。请帮忙。

不能在 C 语言的 if 条件中声明变量...

如果在 if 范围内声明,例如:

if(something){
  int x = 0;
} else{
  x++; // will cause a compilation error
  bar(x);
}
'else' 中的

x 未声明,因为在 C 中,局部变量只能由声明它们的代码块中包含的语句使用。

实验结果:在if条件下不能声明变量。不会编译。

你不能这样声明变量

 if((int a = 0))

编译器不允许代码 运行,你得到一个错误

如果你试试这个

if(something_that_is_false){
        int a = 12;
    }
    else{
        do_something;
    }

再次出错,因为它们处于同一级别并且它们无权访问其局部变量。

警告:您可以使用此代码和 运行s 而不会出错

int a;
    if(a=0){
         printf("True");
    }
    else{
        printf("False");
    }

你会在屏幕上看到 'False' 因为这就像写作

if(0) // and its false!

最后

int a;
    if(a=0){
         printf("True");
    }
    else{
        printf("False");
    }

你会在屏幕上看到 'True' 因为这就像写作

if(5) // 任何非零的数字都是真的!