“break” means, break out of this bit of code.
take this for example:
int i = 0;
while(1){
i++;
if (i == 10){
break; //when i = 10, the break statement is executed and the code jumps...
}
}
//... to here.
Switches are just a convinient way of performing actions depending on the value of a variable.
int j = 2
switch (j)
{
case 1:
// blah
break;
case 2:
// blah
break;
case 3:
// blah
break;
}
could be equally written as:
int j = 2
if (j == 1){
// blah
} else if (j == 2){
// blah
} else if (j == 3){
// blah
}
The two differ when you end up with other operators such as > or <. This works as an if, but not as a switch:
int j = 2
if (j <= 1){
// blah
} else if (j <= 2){
// blah
} else if (j <= 10){
// blah
}
Another use of a switch, which can’t be done with if() is something like this:
switch (nodeOperation) {
case NSNodeNodeBNetA:
//Swap them around so we can use the same code.
tempNode = nodeA;
nodeA = nodeB;
nodeB = tempNode;
case NSNodeNodeANetB:
//Do some stuff here...
break;
case NSNodeKeepMajor:
if (nodeA.net.components.count >= nodeB.net.components.count) {
tempNode = nodeA;
nodeA = nodeB;
nodeB = tempNode;
}
//the nodes are now backwards (node B should be where nodeA is and vice versa) but this will be corrected on fall through
case NSNodeNodeBNetB:
//swap the nodes around to reduce the amount of code required.
tempNode = nodeA;
nodeA = nodeB;
nodeB = tempNode;
case NSNodeNodeANetA:
//do some stuff here.
break;
case NSNodeWireMajor:
if (nodeA.net.components.count >= nodeB.net.components.count) {
tempNode = nodeA;
nodeA = nodeB;
nodeB = tempNode;
}
//the nodes are now backwards (node B should be where nodeA is and vice versa) but this will be corrected on fall through
case NSNodeWireWithB:
tempNode = nodeA;
nodeA = nodeB;
nodeB = tempNode;
case NSNodeWireWithA:
//Do some stuff here.
break;
case NSNodeDontMerge:
default:
return nil; //Cant do this operation as it isn't defined, also, the 'Dont Merge' option comes here
}
By using a switch, I saved a lot of code, as all though there are 9 cases, those cases are essentially grouped into three, the difference being that nodeA and nodeB were switched. So by relying on fall-through as it is known (no break;), the nodes could be switched and use the same code.
(Oh, in case anyone recognises the NS reference in that last bit of code, it is actually written in objective-C, but I have stripped it down to a point which it is perfectly valid in C++ as well.)