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?
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!
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;
}
}
}
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).
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
while (1 != 2) over the likes of while (1) or while (true). Is there a specific reason (like another language) for that - chris 2012-04-03 21:00