I have to implement the following in a switch
statement:
switch(num) { case 4: // some code ; break; case 3: // some code ; break; case 0: // some code ; break; case < 0: // some code ; break; }
Is it possible to have the switch statement evaluate case < 0
? If not, how could I do that?
The switch statement in C/C++ works as follows: (1) first it evaluates the expression presented as a condition in the switch statement. (2) stores the result on the stack or using a general-purpose register.
The expression in the switch can be a variable or an expression - but it must be an integer or a character. You can have any number of cases however there should not be any duplicates. Switch statements can also be nested within each other. The optional default case is executed when none of the cases above match.
Java SE 12 introduced switch expressions, which (like all expressions) evaluate to a single value, and can be used in statements.
I know that this topic is pretty old but if someone still looking for the answer now in C# 7 it's possible. Here is an example:
switch (value) { case var expression when value < 0: //some code break; case var expression when (value >= 0 && value < 5): //some code break; default: //some code break; }
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