根据语言语义制作外部语句的 "else if" 部分?

Making the "else if" part of the outer statement according to language semantics?

假设我们有以下 C 语句:

if( cond) 
      if( cond) 
        stat
      else
        stat

其中 'else stat' 根据语言语义是内部 if 语句的一部分。我需要做什么才能使 'else stat' 成为外部 if 语句的一部分?据我所知,在 then 之后和 if 语句的末尾添加 {} 来分隔它们是可行的。这个对吗?还有另一种方法吗?

在这种情况下,您应该使用复合语句

if( cond1 )
{
      if ( cond2 ) 
        stat;
}
else
{
    stat;
}

另一种从 C 语法的角度来看但可读性较差且不应使用的方法如下

if( cond1 )
      if ( cond2 ) 
        stat;
      else
        ; // empty statement
else
      stat;

然而,可以使用这种方法,然后内部 if 包含另一个 else if。例如

if( cond1 )
      if ( cond2 ) 
        stat;
      else if ( cond3 )
        stat;
      else
        ; // empty statement
else
      stat;

或者可以通过以下方式使其更具可读性

if( cond1 )
      if ( cond2 ) 
      {
        stat;
      }
      else
      {
        ; // empty statement
      }
else
      stat;

您需要使用方括号:

if (cond){
    if (cond)
        //inner conditional 
} else {
  //outer conditional 
}

最佳做法是始终使用括号。它使您自己(或其他人)以后更容易read/understand/modify。

像这样:

if (condition1) {
     if (nestedCondition1) {
        //do something
     }
} else {
    //do something else
}

然后就可以很容易地快速查看您在哪个语句中。