Is the switch register a loop or conditional construct?

I was asked this question in an interview. I replied that this is a conditional construct because

  • It is executed once, unlike a cycle that can execute several times.
  • There are no control mechanisms for the circuit; there is only conditional switching based on different cases.

So my answer is right or wrong, is there a better answer?

And he asked me why the instructions break; work with the switching case, because break; only works with loops. This question I could not answer.

+4
source share
3 answers

In c ++

switch selection-statement

n3376 6.4 / 1 and 6.4.2 is about switch

 selection-statement: ... switch ( condition ) statement 

break jump-statement

n3376 6.6.1 / 1

The break statement should be executed only in the iteration statement or switch statement and cause the completion of the smallest enclosed iteration statement or switch statement; control proceeds to the next statement of the completed statement, if any.

+11
source

C answer

There is no formal term called a conditional construct. The C standard uses a term selection expression. The C language has three different selection operators: if , if-else and switch (C11 6.8.4). Loops are sorted under the iteration category (6.8.5).

The break statement is a jump statement, like goto . It has some restrictions in which it is allowed to appear:

C11 6.8.6.3

The break statement should only appear in the switch body or in the body loop.


So, to answer the interview questions:

Is the switch register a loop or conditional construct?

If you mean a select statement by conditional construction, then yes, switch is a conditional construction.

why break statements; work with the switching case, because break; only works with loops

No, the question is incorrect, it works not only with loops. It works with switch and loops. This is due to the fact that the C language is defined in this way (6.8.6.3).

+4
source

The case of the switch is a way to wrap a block of instructions and execute it (part), starting here and ending here. A case match denotes a beginning, and the next break denotes an end.

A block may contain several instructions:

 { instruction_A; instruction_B; instruction_C; instruction_D; } 

case say where to dynamically run based on the value of switch :

 switch(value) { case one: instruction_A; instruction_B; case two: instruction_C; case three: instruction_D; } 

In the case of one all commands will be called, since there is no gap. Case two will execute C and D if there are no exceptions (c ;.

The break statements tell where to stop, and mean that you can skip several cases:

 switch(value) { case one: instruction_A; instruction_B; case two: instruction_C; break; case three: instruction_D; } 

Case one now execute A, B, and C, but not D.

0
source

Source: https://habr.com/ru/post/1481102/


All Articles