I mentioned that I was learning C# and .NET. And that one of the things that confused me was the requirement to use break in switch statements because fall-through isn't allowed.
At least, according to the book I got from Microsoft. It says, and I quote:
You must repeat the case label syntax for every individual value if you want to run the same statements for more than one value. There is no shortcut for grouping a sequence of case label values. For example:
switch (trumps)
{
case Hearts:
case Diamonds: // error
color = "Red";
break;
case Clubs:
case Spades: // error
color = "Black";
break;
}
and in a sidebar it says:
In C#, fall-through is always a compile-time error. The last statement of a case section is not allowed to fall through to the next case.
And there's nothing in the online errata for this page.
But my other reference says that having multiple case statements all falling together into one block of code is legal, although fall-through from one block of code past a case statement into another block of code is not.
Obviously a test program is required. And it turns out that the Microsoft book is wrong in every particular where it differs from the other volume.
Multiple case statements into one code block are legal. Fall-through from one block of code into another (past a case statement) is a compile-time error.
break is therefore useful, because the front end of the compiler cannot simply assume that a case's block of code is terminated by another case. Without break or something equivalent to indicate the end of a code block, there would be no way to distinguish between:
switch(testValue)
{
case 'A': // not yet implemented
break;
case 'a': // implemented
---some code goes here---
break;
}
and
switch(testValue)
{
case 'A': // handle both upper and lower-case 'A'
case 'a':
---some code goes here---
break;
}
And that's all I have to say about that.
Comments