如果选择上面的if语句,还是会解决吗?

时间:2012-04-03 20:16:04

标签: c++ if-statement

在这组陈述中:

if(robot1Count < 12) {
    robot1Count++;
}
else if(robot1Count < 24) {
    robot1Count++;
}
else if(robot1Count < 36) {
    robot1Count++;
}
else if(robot1Count < 48) {
    robot1Count++;
}
else {
    robot1Count = 0;
}

想象一下,这是一个无限循环,这个循环是否会从0遍历到48,变为0.我想知道的是,如果第一个块被执行,是否会忽略以下所有块?或者我应该将第二个更改为else(robot1Count&lt; 24&amp;&amp; robot1Count&gt; = 12)?或者那不重要吗?

5 个答案:

答案 0 :(得分:7)

  

我想知道的是,如果第一个块被执行,是否会忽略以下所有块?

是的,他们都会被忽略。甚至不会评估条件。但是你知道,你可以亲自测试一下!

if(robot1Count < 12) {
    printf("< 12");
    robot1Count++;
}
else if(robot1Count < 24) {
    printf(">= 12 && < 24");
    robot1Count++;
}
else if(robot1Count < 36) {
    printf(">= 24 && < 36");
    robot1Count++;
}
else if(robot1Count < 48) {
    printf(">= 36 && < 48");
    robot1Count++;
}
else {
    printf(">= 48");
    robot1Count = 0;
}

然后你可以看到哪些消息被打印到控制台,然后你就会知道并感受到正在发生的事情!

答案 1 :(得分:4)

此:

if (cond1)
    stuff1;
else if (cond2)
    stuff2;
else if (cond3)
    stuff3;
else
    stuff4;

完全相同

if (cond1) {
    stuff1;
}
else {
    if (cond2) {
        stuff2;
    }
    else {
        if (cond3) {
            stuff3;
        }
        else {
            stuff4;
        }
    }
}

答案 2 :(得分:2)

是的 - 如果if分支执行elseif分段和if语句的else分段是互斥的不(反之亦然)。

答案 3 :(得分:1)

当然,除非你将“else if”切换为“if”

,否则它们将被忽略

答案 4 :(得分:1)

如果上面的代码是无限循环

例如

int robot1Count = 0;
while (1 != 2) {

if(robot1Count < 12) {
    robot1Count++;
}
else if(robot1Count < 24) {
    robot1Count++;
}
else if(robot1Count < 36) {
    robot1Count++;
}
else if(robot1Count < 48) {
    robot1Count++;
}
else {
    robot1Count = 0;
}
}

在一个循环中,这将增加到48并返回到0

每次执行循环只会命中robot1Count ++