The label is just a name to identify a line where a code snippet starts.
His idea comes from using goto
, the command that deviates the execution flow directly. This command is always followed by a name of label existing in that function. Then you put a name somewhere just to mark that there is the location of the code where a snippet and the goto
will deviate precisely to the instruction that comes first just after the label.
Note that after the compiled code this name disappears and instead the address of the code location where the deviation will take place.
Example:
inicio: //isto é um label
printf("Hello");
goto inicio;
This code keeps writing the word non-stop on the screen because every time you get to that third line you have to switch to the first one, since that’s the name used. Like label does not actually exist as the execution factor the command to be executed is that of printf()
and then fall into goto
again.
His syntax is his name and then :
, so do not confuse with a variable or other type of code symbol.
It is clear that this does not generate scope new and one of the reasons it’s not a command block. The whole code there is one thing, it doesn’t differ from other parts right there, different from the use of the keys that makes those commands inside them something with a certain isolation in a certain point of view and creates a kind of hierarchy in the code having a part inside another part.
A switch
is a huge goto
calculated. Depending on the value found it gives a goto
to a different location. The compiler mounts a table with the corresponding values and the location to which it should deviate. That place that should divert is the label, only a name indicating where that location is.
But that inside the switch
the label has a slightly different syntax always starting with a case
followed by a value that will be used to mount this switch
.
You realize he also uses the two dots equal to the label of goto
? It does not use keys, so a new block and command is not generated. [It is possible to use keys inside to generate a block of commands, but this is orthogonal, is another mechanism not related to switch
.
They thought the syntax became more linear, after all the switch
is a special case of goto
and that the command block, if necessary, could still be used normally, and would not need to force its use. It would probably give a little more flexibility. Otherwise I think there is an explanation in the original question.
To understand more about the calculation of goto
read How the switch works behind the scenes?.
Pq a label is faster on Assembly and, as already answered in the question, it is interesting to have an option with shared scope.
– aviana