Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 625
Andrew Avatar asked May 24 '11 04:05

Andrew


People also ask

What is switch statement example?

So, printf(“2+3 makes 5”) is executed and then followed by break; which brings the control out of the switch statement. Other examples for valid switch expressions: switch(2+3), switch(9*16%2), switch(a), switch(a-b) etc.

What type of statement is switch?

A switch statement is a control statement that executes a set of logic based on the result of a comparison between a controlling expression and the labels specified in the switch block.

What happens in a switch statement?

A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case.

What is a switch statement in JavaScript?

Definition and Usage. The switch statement executes a block of code depending on different cases. The switch statement is a part of JavaScript's "Conditional" Statements, which are used to perform different actions based on different conditions. Use switch to select one of many blocks of code to be executed.


1 Answers

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.

like image 108
Harry Joy Avatar answered Sep 25 '22 02:09

Harry Joy