Reputation: 3142
In this set of statements:
if(robot1Count < 12) {
robot1Count++;
}
else if(robot1Count < 24) {
robot1Count++;
}
else if(robot1Count < 36) {
robot1Count++;
}
else if(robot1Count < 48) {
robot1Count++;
}
else {
robot1Count = 0;
}
Imagine this is in an infinite loop, would this loop traverse from 0 to 48, change to 0. The thing I'm wondering is if the first block is executed, would all the following blocks be ignored? Or should I change the second to else if(robot1Count < 24 && robot1Count >= 12) ? Or does that not matter?
Upvotes: 0
Views: 113
Reputation: 241651
The thing I'm wondering is if the first block is executed, would all the following blocks be ignored?
Yes, they will all be ignored. The conditions won't even be evaluated. But you know, you could have tested this yourself!
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;
}
And then you can see which messages are printed to the console and then you'd know and feel what is going on!
Upvotes: 7
Reputation: 2349
if the code above is in a infinite loop
example
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;
}
}
in a loop this will increment to 48 and go back to 0
it will only hit robot1Count++ per single execution of the loop
Upvotes: 1
Reputation: 490178
Yes -- the if
leg and the else
leg of an if
statement are mututally exclusive -- if the if
leg executes the else
does not (and vice versa).
Upvotes: 2
Reputation: 272537
This:
if (cond1)
stuff1;
else if (cond2)
stuff2;
else if (cond3)
stuff3;
else
stuff4;
is identical to this:
if (cond1) {
stuff1;
}
else {
if (cond2) {
stuff2;
}
else {
if (cond3) {
stuff3;
}
else {
stuff4;
}
}
}
Upvotes: 4
Reputation: 3260
Of course they will be ignored, unless you switch the "else if" to "if"
Upvotes: 1