Switch statement fallthrough is one of my personal major reasons for loving switch vs. if/else if constructs. An example is in order here:
static string NumberToWords(int number) { string[] numbers = new string[] { '', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine' }; string[] tens = new string[] { '', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety' }; string[] teens = new string[] { 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen' }; string ans = ''; switch (number.ToString().Length) { case 3: ans += string.Format('{0} hundred and ', numbers[number / 100]); case 2: int t = (number / 10) % 10; if (t == 1) { ans += teens[number % 10]; break; } else if (t > 1) ans += string.Format('{0}-', tens[t]); case 1: int o = number % 10; ans += numbers[o]; break; default: throw new ArgumentException('number'); } return ans; }
The smart people are cringing because the string[]s should be declared outside the function: well, they are, this is just an example.
The compiler fails with the following error:
Control cannot fall through from one case label ('case 3:') to another Control cannot fall through from one case label ('case 2:') to another
Why? And is there any way to get this sort of behaviour without having three ifs?
(Copy/paste of an answer I provided elsewhere)
Falling through
switch–cases can be achieved by having no code in acase(seecase 0), or using the specialgoto case(seecase 1) orgoto default(seecase 2) forms: