I have a switch statement that is based off an int comparison, but for some reason, it keeps failing on true comparisons, and skipping to the default. Here's my code:
string Error(int errorNum, int send=1, int crash=1)
{
string errorType;
switch(errorNum)
{
case 10:
errorType = "Port number";
...
default:
errorType = "Unknown";
}
...
}
I keep calling it with the argument of 10, but when I do, it fails. The equivelant if... else if... else method works, and here it is as well:
string Error(int errorNum, int send=1, int crash=1)
{
string errorType;
if (errorNum == 10) // Normally I'd use braces,
errorType = "Port number"; // but here, it just clutters
...
else
errorType = "Unknown";
...
}
You are likely missing a break in the case. Make sure that at the end of each case you include break or it will fall through to the next one.
string Error(int errorNum, int send=1, int crash=1)
{
string errorType;
switch(errorNum)
{
case 10:
errorType = "Port number";
break; // If this is not here it will fall throughto the next case or default
default:
errorType = "Unknown";
}
return errorType;
}
If you don't use break then the all the subsequent case statements will be executed after the matching case.
So in your your case, it executes both the case parts and overwrites the value errorType which gives you the impression that it directly jumps to default case.
To add an interesting update...
Note that having braces around case statements would make no difference. In fact, the following code is valid C++ and would work as expected:
switch(var)
{
{
case 1:
cout<<"case 1"<<endl;
}
cout<<"This is also part of case 1"<<endl;
case 2:
{
cout<<"case 2 "<<endl;
}
}
Note the braces are NOT misplaced.
Here the outside cout is also a part of the case 1. After evaluating the control expression var, control will jump straight to the matching case. The braces around case 1 merely introduces a new scope and has no bearing over what a case really constitutes. So right way is to put break statements if you don't want to fall-through the rest of cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With