Switch with multiple statements for same case - switch-statement

I would like to use an statement for multiple cases and then an extra statement for a single case.
switch (i)
{
case 1:
case 2:
statement1;
break;
case 1:
statement2;
break;
}
So for case 1 statement1 and statement2 should be executed.

You could delete the second case 1 in your code and move statement2 to your first case 1. But this only works if the order of the statements is not important (i.e. statement2 can be executed before statement1):
switch (i)
{
case 1:
statement2;
//Fall through
case 2:
statement1;
break;
default:
pleaseDoNotForgetMe();
}
If the order is important, I think you have no choice but give each case its break:
switch (i)
{
case 1:
statement1;
statement2;
break;
case 2:
statement1;
break;
default:
pleaseDoNotForgetMe();
}

Related

swift case falling through

Does swift have fall through statement? e.g if I do the following
var testVar = "hello"
var result = 0
switch(testVal)
{
case "one":
result = 1
case "two":
result = 1
default:
result = 3
}
is it possible to have the same code executed for case "one" and case "two"?
Yes. You can do so as follows:
var testVal = "hello"
var result = 0
switch testVal {
case "one", "two":
result = 1
default:
result = 3
}
Alternatively, you can use the fallthrough keyword:
var testVal = "hello"
var result = 0
switch testVal {
case "one":
fallthrough
case "two":
result = 1
default:
result = 3
}
var testVar = "hello"
switch(testVar) {
case "hello":
println("hello match number 1")
fallthrough
case "two":
println("two in not hello however the above fallthrough automatically always picks the case following whether there is a match or not! To me this is wrong")
default:
println("Default")
}
case "one", "two":
result = 1
There are no break statements, but cases are a lot more flexible.
Addendum: As Analog File points out, there actually are break statements in Swift. They're still available for use in loops, though unnecessary in switch statements, unless you need to fill an otherwise empty case, as empty cases are not allowed. For example: default: break.
Here is example for you easy to understand:
let value = 0
switch value
{
case 0:
print(0) // print 0
fallthrough
case 1:
print(1) // print 1
case 2:
print(2) // Doesn't print
default:
print("default")
}
Conclusion: Use fallthrough to execute next case (only one) when the previous one that have fallthrough is match or not.
The keyword fallthrough at the end of a case causes the fall-through behavior you're looking for, and multiple values can be checked in a single case.

Switch statement bigger than

How to make a switch statement condition look like this:
if(age>18)
I want it to look like this, but then in a switch-statement version.
Is this possible?
Depends on the language you use.
C# => Not possible: switch case
Each case label specifies a constant value.
Java => Not possible: switch case
An if-then-else statement can test expressions based on ranges of
values or conditions, whereas a switch statement tests expressions
based only on a single integer
You will have to use an if-elseif-elseif-else approach in case you use Java or C#.
Javascript => Possible: switch case
case expressionN A case clause used to match against expression.
switch (true) {
case age > 18:
document.write("You are older than 18");
break;
}
mostly the switch statements are used when you are exactly matching the phrase.
switch (age>18)
{
case true:
//Do something
break;
case false:
//Do something
break;
}
In your case use if condition.It will also gives you better way to check your data.If your age is less than 18 or any other case.
if(age>18)
{/* Do something if your condition is true */ }
else
{ /* When your condition is false */ }
Yes, it's possible with a sort of 'reverse condition' trick - if that's supported by the language used, of course. That's how it looks in JavaScript:
function checkAge(age) {
switch (true) {
case age < 18:
console.log('Really young');
break;
case age < 25:
console.log('Young and proud');
break;
case age < 32:
console.log('Mature and proud');
break;
default:
console.log('Well, I got some news for you...');
}
}
checkAge(17); // Really young
checkAge(24); // Young and proud
checkAge(31); // Mature and proud
The trick is that each subsequent case value is checked against the expression specified as switch value. Still, as you need to delimit each section with break, I really doubt that's more readable than if-else statement.
You haven't specified a language, but the below construct is possible in languages which take an expression in the switch, viz:
switch (age>18)
{
case true:
// Do over 18 stuff here
break;
case false:
// Do under 18 stuff here
break;
}
Although this works, this wouldn't be an intuitive branching technique so readability of the code may suffer - use of if / then else for branches, or the conditional operator for conditional evaluation would be more common.
in php you can do:
switch($age) {
case ($age < 17):
print "do something";
break;
case ($age > 18): print "over 18"; break;
}
Technically you can put it like that (C# code sample):
switch (age) {
case 0:
case 1:
case 2:
...
case 18:
break;
default: // <- if(age>18)
...
break;
}
but do you really want it? In C#, Java etc. we usually use if else:
if (age <= 5) { // from 0 up to 5
...
}
else if (age <= 10) { // from 5 up to 10
...
}
else if (age <= 18) { // from 10 up to 18
...
}
else { // over 18
...
}
In case of a SQL dialect (where often you don't have if construction) you can put it like that:
case
when (age > 18) then
...
else...
end
for instance
select case
when (age > 18) then
'Over 18'
else
'18 or under 18'
end
from MyTable

Javascript: on/off switch

What is wrong whith this code? I have tested it many times but something still doesn't work.
var playernow = 1; //Whose player's turn it is (1 or 2)
function bobenli(playernow){
var wert="";
switch (playernow){
case "1":
wert="X";
playernow=2;
case "2":
wert="O";
playernow=1;
}
alert(playernow);
}
No break statement, both cases get executed. Also as others have said you are comparing ints to strings. You can drop the quotes in the cases.
var playernow = 1; //Welcher Spieler dran ist )(1 oder 2)
function bobenli(playernow){
var wert="";
switch (playernow){
case 1:
wert="X";
playernow=2;
break;
case 2:
wert="O";
playernow=1;
break;
}
alert(playernow);
}
var playernow = 1; //Welcher Spieler dran ist )(1 oder 2)
function bobenli(playernow){
var wert="";
switch (playernow){
case "1":
wert="X";
playernow=2;
break;
case "2":
wert="O";
playernow=1;
break;
}
alert(playernow);
}
you missed break statement in following switch case... http://jsfiddle.net/yjusC/
You need a break at the end of each case:
switch (playernow){
case "1":
wert="X";
playernow=2;
break;
case "2":
wert="O";
break;
First: no break, second: you're comparing different types (int and string). This might have no impact now, but you should be careful in general.
case "1": // This is looking for a string. You set playernow equal to an integer value above.

Double or single switch

Well it might be a dumb question, but I'm unable to find an answer:
The case is simple, I have a function with an integer in entry and two variable to assign depending of that. The problem is that the value assigned to the variables is common to certain case, but those case are not the same for the two variables. (if it's not clear enough, see the example).
I was wondering what was the best practice for such a case.
Is it something like :
function test(a){
var x,y;
switch (a){
case 0:
case 1:
case 7:
y=...;
break;
case 2:
case 6:
y=...;
break;
case 3:
case 4:
case 5:
y=...;
}
switch(a){
case 5:
case 6:
case 7:
x=...;
break;
case 0:
case 4:
x=...;
break;
case 1:
case 2:
case 3:
x=...;
}
...
}
or
function test(a){
var x,y;
switch (a){
case 0:
x=...;
y=...;
break;
case 1:
x=...;
y=...;
break;
case 2:
x=...;
y=...;
break;
case 3:
x=...;
y=...;
break;
case 4:
x=...;
y=...;
break;
case 5:
x=...;
y=...;
break;
case 6:
x=...;
y=...;
break;
case 7:
x=...;
y=...;
}
...
}
Or to use a mix of the two with the value assigned to x in each case and to make groups for the value of y?
Note that there might be more than 8 value, it's just for the example.
Thanks in advance.
If there's no real overlap between the different cases in the switch statements, you're probably better off having them separate.
If there was a majority of commonality between the actions, you could combine them with certain special cases within the individual case blocks but you seem to indicate that's not the case here.
However, if this isn't just a simple example of a much more complex case, you can achieve a more compact solution with something like:
// index: 0 1 2 3 4 5 6 7 8 9 10 11 12
static const int lookupX[] = { 2, 7, 1, 8, 2, 8, 1, 8, 2, 8, 4, 5, 9};
static const int lookupY[] = { 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9};
if ((a >=0) && (a < sizeof(lookupX) / sizeof(*lookupX)))
x = lookupX[a];
if ((a >=0) && (a < sizeof(lookupY) / sizeof(*lookupY)))
y = lookupY[a];
This will allow you to keep the values in a much smaller "configuration" section so that you can easily see the intent. The range checking and lookup then become very simple.
That code is tailored to C - I'm not sure what specific language you're using (because of the var statement) but it's basically only doing the lookup if the index will be valid. You'll need to translate that bit to your language of choice.

Can I jump from one case to another in a switch statements?

For switch statements, is it possible to change the value of the switch inside the switch statement so that it can jump around to different cases?
Ex:
int w = 0;
switch(w)
{
case 1:
doSomething();
w = 3;
case 2:
doSomething();
break;
case 3:
doSomething();
break;
}
Basically what I'm asking is, if I do not place a break statement for a case and I change the value of the switch in the same case, will the code execute both cases?
Yes you can change the value inside switch but it will not execute case for new value until you break in the case where you changed the value.
In your case it will not go in any case as there is no case for 0. But if you change to w = 1 then it will go for case 1 and then for case 2 as you do not have break; but it will not go for case 3.
No, it will not change and will not execute new case statement.
Remember that, once appropriate match is found with the case statement corresponding to a value inside the switch statement, that particular case is executed and once that is executed ( if break is provided after each case to prevent falling through all cases) , then the control returns to the end of switch statement.
Sample Code :
public class A {
public static void main(String [] args) {
int i=1;
switch(i) {
case 1 :
System.out.println("Case 1");
i = 2;
break;
case 2 :
System.out.println("Changed to Case 2");
break;
default:
System.out.println("Default");
break;
}
System.out.println("Final value of i " + i);
}
}
Output :
Case 1
Final value of i 2
Note : Inserting proper breakpoints, try to debug. You will come to know yourself, what exactly is happening.
If we do not give break after each case then Java will start executing the statement from matching case and keep on executing statements for following cases as well, until either a break statement is found or switch statements end is encountered.
If case 1 happens to execute, it's just a fall through to the case 2. And since there is a break in case 2, further fall through doesn't happen. It doesn't jump to case 3 because of the statement w = 3 ; in case 1.
No the switch's case will not change when changing the value in a particular case it checks only once
let a = 1
switch (a) {
case 1:
console.log("Hello from 1")//only this will be printed
a = 2//value of a is changed
break
case 2:
console.log("hello from 2")//this will not execute
a = 3
break
case 3:
console.log("hello from 3")//this will not execute
a = 4
break
case 4:
console.log("hello from 4")//this will not execute
break
default:
console.log("default")
}
console.log(a)//value will be 2

Resources