So I recently learned about switch statements so I know that they are used as a replacement for if statements. For example,
if statement-
if (x == 1){do function(a)}
if (x == 2){do function(b)}
…
So, this can be written as-
switch(x){
case 1: do function(a);
case 2: do function(b);
}
Switch statements can only be used where there are defined constants to compare with as you gave in the first example.We cannot write switch statements with relational operators. Only option then is to use if-elseif-else.
However, if there are some cases for which you want to call the same function,you can use this:
switch(x){
case 1:
case 3:
case 5:
case 7:
case 9:{
isOdd(true);break;
}
default : isEven(true);
}
This checks if a single digit number is odd.This takes advantage of fall-through and can be useful at some cases.But you cannot use switch case properly without well defined conditions.
Also remember that you can only check for equality in case of a switch-case construct.
Hope this helps.
@mathecodician It is known as fall-through behaviour of C++, i.e., if you don’t write break statement in switch case., control switches to the next case until break statement is found. So, in your code control goes to case 7 in which there is no break statement, so control will transfer to case 9 which will make isOdd=true and then it will come out of Switch case.
unlike in some languages (like BASIC and some others…) most languages support fall through that is if the command enters a case and does not find a break statement at the end, then it just starts executing the cases BELOW it as well until it reaches a break or the end of the switch statement.This is called fall-through.However, you should use this concept sparingly.
Hello @mathecodician, if you write many cases and then define, it means you have defined that action for all above cases. Moreover, you don’t need those braces for those cases inside switch. Also, consider using separate headers than a single master header, though it might seem to you that this reduces time to write, it also makes debugging difficult and may not work on all compilers