The switch jumps to the case that matches. Then it executes all lines from that point onward.
For example, if z=='/', then execution jumps from line 1 to line 9 (over lines 2-8). The 'default' is a "catch all".
A
break;
within scope of switch jumps out from the scope, (here to line 17). The default case reaches the end anyway, so does not need a break-out.
You could use this:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
switch ( z )
{
case 'n':
case 'N':
home();
break;
case 'y':
case 'Y':
bar();
break;
case default:
std::cout << "unknown selection: '" << z << "'\n";
}
|
Here both 'n' and 'N' lead to home(), both 'y' and 'Y' to bar(), and anything else is, well, unexpected.
Overall, switch seems to have less use.
There is yet another approach. A more dynamic one. Imagine a table with two columns. The first has a "key" (like the -, +, /, *). The second column has a "value".
We don't need to know the size of the table during compilation. We can fill it during runtime.
Now, rather than having ifs or a switch, we search key from the table. If we do find it, then we can pick the corresponding value.
It is possible to store a function's address in an object (in value) and call the function with that address. For example, find key '/' from table and "calling" the corresponding value executes the divide().