没有括号的 if 语句

Phl*_*sh6 5 c if-statement

我希望能得到一些澄清ifif else声明没有括号以及如何阅读它们。我可以轻松阅读if else, 和else if带括号的语句,它们对我来说很有意义,但这些总是让我感到困惑,这里有一个示例问题。

if (x > 10)      
     if (x > 20)
          printf("YAY\n");    
else      printf("TEST\n");
Run Code Online (Sandbox Code Playgroud)

Mur*_*nik 6

没有括号, the elsewill 与ifit 紧接其后有关。因此,要正确插入您的示例:

if (x > 10)      
     if (x > 20)
          printf("YAY\n"); 
     else // i.e., x >10 but not x > 20
          printf("TEST\n");
Run Code Online (Sandbox Code Playgroud)


小智 6

如果 if/else 上没有括号,则将执行 if 之后的第一条语句。

如果语句:

if (condition)
    printf("this line will get executed if condition is true");
printf("this line will always get executed");
Run Code Online (Sandbox Code Playgroud)

如果别的:

if (condition)
    printf("this line will get executed if condition is true");
else
    printf("this line will get executed if condition is false");
printf("this line will always get executed");
Run Code Online (Sandbox Code Playgroud)

注意:如果在 if 与其匹配的 else 之间有多个命令,您的代码将会中断。

if (condition)
    printf("this line will get executed if condition is true");
    printf("this line will always get executed");
else
    printf("this else will break since there is no longer a matching if statement");
Run Code Online (Sandbox Code Playgroud)