Is the "opt" after "switch" required?
Well, no. There you need an expression that gives some value that can be compared to the case
options. Usually it's a variable, but it does not have to be, much less it needs to be opt
. It may, but it does not make sense to have a literal, if you already know the value you do not have to compare.
switch
always takes this value and finds which of the case
s that fits in it, only one can be executed directly. But others can run in sequence indirectly, so the case
that it enters because its literal (and case
must always have a literal) is equal to the value of switch
will be first, then it keeps coming in in all% s of% s following.
This helps because you often want to make a kind of case
, that is, more than one value is accepted, whichever one it enters must execute all of the following execution blocks. It is common that in these cases only the last or
that should do something have a code, the others are empty, like this:
switch (variavel) {
case 1:
case 2:
case 3:
printf("entrou");
}
Is the "break" command too?
But doing this is not very useful, you will want it to stop running at some point, you can not have it done because there the case
is no longer useful, you are not selecting anything.
This is where switch
comes in, you use it to say that this block should be closed. Note that the moment you find break
break
everything is terminated. That's better:
switch (variavel) {
case 1:
case 3:
printf("impar");
break;
case 2:
case 4:
printf("entrou");
}
Why does not it appear after the 'case' options? ' "and" default "?
You see that I did not use switch
at the end. Why would I use it? In the end it closes itself. No need. But many people even put it in order to organize, to make it more readable, to identify the intention and to facilitate a change that adds some block without the risk of forgetting to put the break
that now becomes necessary.
The same goes for break
, you do not have to have something closed down.
You may wonder why the last default
did not need case
and break
exists then. The default
is special, it only enters it if it does not enter the previous blocks, it is an execution OU, there is no way to enter it if it entered some default
. It's another name, the compiler knows that it has closed before.
No case
nobody puts default
does not make sense because no point of view is.