"Opt" after "switch" is required?
Well, no. There is an expression that gives some value that can be compared with the options of case
. It’s usually a variable, but it doesn’t have to be, much less it has to be opt
. Can, but it doesn’t make sense to have a literal, if you already know the value has no reason to compare.
The switch
always take this value and find out which case
s that fits into it, only one can be executed directly. But others can perform in sequence indirectly, then the case
that he enter because of his literal (and in case
always must have a literal) is equal to the value of switch
will be the first, then he continues to enter into all the case
s following.
This helps because often you want to do a kind of or
, that is, more than one value is accepted, anyone he enters must execute all of the following execution blocks. It is common that in these cases only the last case
that must do something have a code, the rest are empty, so:
switch (variavel) {
case 1:
case 2:
case 3:
printf("entrou");
}
The "break" command also?
But to do this is not very useful, you will want him to stop executing at some point, you can not have to do all because there the switch
no longer useful, you are not selecting anything.
That’s where the break
, you use it to say that this block should be closed. Note that at the time you find the break
the switch
all is closed. So it gets better:
switch (variavel) {
case 1:
case 3:
printf("impar");
break;
case 2:
case 4:
printf("entrou");
}
I put in the Github for future reference.
Why it does not appear after the options "case '?' and "default"?
You saw I didn’t use the break
in the end. Why would I use it? In the end it ends even. No need. But many people put so anyway to organize, make more readable, identify the intention and facilitate a change that adds some block without risking forgetting to put the break
which now becomes necessary.
The same goes for the default
, there’s no point in having something shut down.
You may wonder why the last case
did not need the break
where there is the default
next. The default
it is special, only enter it if it does not enter the previous blocks, it is an OR of execution, there is no way to enter it if it entered in some case
. It’s another name, the compiler knows it closed before.
In the default
no one puts break
makes no sense from any sane point of view.
Thank you! Just two questions: 1) "Can, but it doesn’t make sense to have a literal" what does literal mean in this context? 2) "The switch always brings this value and finds out which case fits it, only one can be executed directly" I didn’t understand your phrase, what is this 'ga'?
– Klel
Literal is the same value, a number, a text, not a variable, constant, expression. I tidied up the text
– Maniero