If a user enters 2 then Good! will be printed twice.
I would have expected it to behave like an if ... else if .... else .... end statement and as soon as the condition is hit the code stops (or moves on)
I understand that as soon as a case is true that all code until break beneath that is executed so the bit I don't understand is what purpose does this logic serve?
Put "break;" right before each new case. Without breaks, it will execute all the code from whatever case they select all the way down to the first break it finds, without stopping at a new case. So just put
1 2 3 4
case 5: cout << "Good!" << endl;
break;
case 4: // .... etc
Thanks freddy92 but I already understand that break is required to stop forward processing but my question is why? It seems to me that hitting a case is in itself reason to look no further? I don't understand why break is required. This I suppose is more of a C++ history/philosophy question! :-)
I believe it was simply a mistake, due largely because when C was designed there was not nearly as much experience with how these constructs would be used.
But I do exploit fall-through in the following sort of situation:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
void DumpData(short port, unsignedchar* data, int data_size)
{
switch(port)
{
case HTTP:
case FTP:
case SMTP:
DumpStrData(data, data_size);
break;
case LDAP:
DumpBerEncData(data, data_size);
break;
default:
DumpBinData(data, data_size);
}
}
I don't put a break after the default case, but do always make sure it's the last one. A habit I picked up early in my programming life.
P.S. Another common case -- from an old school modal dialog's DialogProc
...
case WM_COMMAND:
{
int id = LOWORD(wParam);
switch(id)
{
case IDOK:
case IDCANCEL:
EndDialog(hWnd, id);
break;
case IDC_RESET:
ResetAll(); // for example
break;
default:
{ /* nothing to do */ }
}
}
return TRUE;
...
Thanks andywestken, I was getting concerned that the logical part of my brain had detached as I just couldn't see the reason for it, my Google skills were also failing me so that may well still be the case!
The /* FALLTHRU */ comment make a lot of sense for me as it means I have to type something after each case to imply behavior.