【问题标题】:Short circuiting if statement短路 if 语句
【发布时间】:2021-08-20 23:23:08
【问题描述】:

假设你有这个嵌套的 if 语句:

int *x;
int y;
if (x == NULL || y > 5)
{
  if (x != NULL)
    // this should print if x != NULL and y > 5
    printf("Hello!\n");
// this should only print if x == NULL.
printf("Goodbye!\n");
}
return 0;

这里,如果任一语句为真,它将返回相同的值 (0)。如果外部 if 语句的左侧为真,我们应该只打印“再见”,而不管右侧是真还是假。是否可以通过短路来消除内部 if 语句,将其变成单个 if 语句?

【问题讨论】:

  • 在这种特定情况下,短路行为不会改变任何东西。你的问题不清楚。
  • 代码中的cmets暗示在第二个printf()之前应该有一个else
  • @EugeneSh。我会编辑我的问题。我很好奇是否可以通过短路来消除内部 if 语句。
  • @user12787203 您应该以清晰易懂的方式编写代码,并将优化留给编译器。
  • 通过“短路”你可以完全消除ifs:(x==NULL && printf("Goodbye!\n")) || (y > 5 && printf("Hello!\n"));。并不是说我鼓励这种风格。

标签: c if-statement short-circuiting


【解决方案1】:

如果我理解正确,您需要的是以下内容

if ( x == NULL )
{
    printf("Goodbye!\n");
}
else if ( y > 5 )
{
    printf("Hello!\n");
}

否则,如果第一个复合语句包含在 x == NULL 或 y > 5 时必须执行的其他语句,则 if 语句可能看起来像

if ( x == NULL || y > 5)
{
    // common statements that have to be executed when x == NULL or y > 5
    //...
    if ( !x )
    { 
        printf("Goodbye!\n");
    }
    else
    {
        printf("Hello!\n");
    }
}

【讨论】:

    【解决方案2】:

    这只会在 x 为 NULL 且 y > 5 时打印 Goodbye

    if (x == NULL || y > 5)
    {
      if (x != NULL)
        // this should print if x != NULL and y > 5
        printf("Hello!\n");
      else
        // this should only print if x == NULL.
        printf("Goodbye!\n");
    }
    

    【讨论】:

      猜你喜欢
      • 2013-02-15
      • 2016-03-26
      • 2017-08-23
      • 2019-10-18
      • 2011-06-30
      • 2015-02-13
      • 2013-09-11
      • 2017-02-26
      • 2012-07-05
      相关资源
      最近更新 更多