Reputation: 494
- (void)change:(int)a {
int number = a;
int max = 10;
switch(max) {
case number:
//Do something
break;
//.... more cases
}
}
This is just a small example of the issue I can't seem to solve. I have looked at similar posts and answers usually include using constants via a #define or enum, however these are great when you have a constant that is fixed but if the value is passed through as a parameter how could I do this? if it's possible at all. Any advice would be appreciated.
Upvotes: 0
Views: 408
Reputation: 17623
A switch statement is used to test the value of a variable against a list of constant expressions. The difference between a switch with its various case statements and a series of if/elseif statements for the same comparisons is more of a syntax difference than a logic difference.
However the if/elseif statements are more flexible since they do not require constant expressions and you can also use more complex logical expressions in the if/elseif as well.
For instance:
switch (iValue) {
case 1:
break;
case 4:
break;
default:
break;
}
has the same meaning as this series of if/elseif statements:
if (iValue == 1) {
} else if (iValue == 4) {
} else {
}
Most of the time a compiler will generate a series of if/elseif code when it is generating the code for a switch statement. So the actual code generated by the compiler for an if/elseif statement series is similar to the code generated for a switch statement.
Upvotes: 0
Reputation: 163288
In a nutshell, case
statements can only operate on constant expressions, so if you need more dynamic conditionals, you will have to use if
statements.
Upvotes: 3