短路if语句

时间:2021-06-02 19:18:39

标签: c if-statement short-circuiting

假设你有这个嵌套的 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 语句的左侧为真,我们应该只打印“Goodbye”,而不管右侧是真还是假。是否可以通过短路消除内部if语句,将其变成单个if语句?

3 个答案:

答案 0 :(得分: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");
    }
}

答案 1 :(得分:0)

这只会在 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");
}

答案 2 :(得分:-1)

您可以使用 break; 语句。它打破了声明。 例如:

int *x;
int y;
if (x == NULL || y > 5)
{
  if (x != NULL){
    printf("Hello!\n");
    break;
  }
printf("Goodbye!\n");
}
return 0;
相关问题