+ 2
Explain switch
5 odpowiedzi
+ 6
The switch statement transfers control to one of the several statements, depending on the value of a condition.
+ 4
Switch is an alternative to writing multiple if statements checking for the value of a variable.
int x = 2;
switch (x)
{
case 1:
cout << "x is 1";
break;
case 2:
cout << "x is 2";
break;
default:
cout << "x is not 1 or 2";
}
We break after each case in order to exit the switch statement and continue with the program, otherwise multiple cases may run (if we didn't have a break on case:1, and x was 1, then case:1 and case:2 would run).
This isn't the case on the final case in a switch statement, as it is only going to exit anyway, so you're welcome to save yourself a line. Default is the case that is used if x does not fit any of the other cases; this is optional.
+ 1
Switch statements can be used if you expect some specific strings, numbers, chars etc. In this case it's less code to Write and looks nice. But from the viewpoint of the performance, it is slower than if blocks, because the switch block will be converted in a regular if else block before at can be executed.
Syntax:
switch(number) {
case 1: System.out.println(1);
break;
case 100: System.out.println(100);
break;
default: System.out.println("this is executed if none of the cases above is executed");
}
0
a switch statement is used kinda like a giant (or lesser) if else if else statement. for example if we have:
int x;
cin >> x;
switch (x)
{
case 5:
cout << "x is 5";
break;
default:
cout << "x is not 5";
break;
}
something to note is that switch statements do not support comparison operators like < > ||. however you can do something like case 5 : case 6: case 7
and so on and so forth for an or operator. I usually use switch statements if I'm looking for and specific answer or a few different answers rather than a range of answers
0
a switch is a better and faster alternative to a nested if statement that is normally used to control logic in your code.