首页 > 解决方案 > 短路 if 语句

问题描述

假设你有这个嵌套的 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 语句?

标签: cif-statementshort-circuiting

解决方案


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

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");
    }
}

推荐阅读