CodeCrusader
CodeCrusader

Reputation: 579

Is switch case a loop or a conditional construct?

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

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

Also he asked me the reason why break; statements work with switch-case since, break; only works with loops. This question I could not answer.

Upvotes: 4

Views: 5636

Answers (3)

Lundin
Lundin

Reputation: 213286

C answer

There is no formal term called "conditional construct". The C standard uses the term selection statement. The C language has three different selection statements: if, if-else and switch (C11 6.8.4). Loops sort under the category of iteration statements (6.8.5).

The break statement is a jump statement, just like goto. It has some restrictions of where it is allowed to appear:

C11 6.8.6.3

A break statement shall appear only in or as a switch body or loop body.


So to answer the interview questions:

Is switch case a loop or a conditional construct?

If you by conditional construct mean a selection statement, then yes, switch is a conditional construct.

why break; statements work with switch-case since, break; only works with loops

No, the question is incorrect, it does not only work with loops. It works with switch and loops. This is because the C language is defined in that way (6.8.6.3).

Upvotes: 7

Open AI - Opting Out
Open AI - Opting Out

Reputation: 24133

A switch case is a way of wrapping a block of instructions and saying execute (part of) it, beginning here and ending here. The matching case marks the beginning and the following break marks the end.

The block could be a few instructions:

{
     instruction_A;
     instruction_B;
     instruction_C;
     instruction_D;
}

The case statements say where to dynamically start based upon the switch value:

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

In case one, all the instructions will be called, as there is no break. Case two will execute C and D, if there are no exceptions (c;.

The break statements say where to stop, and mean it's possible to drop through a number of case statements:

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

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

Upvotes: 0

ForEveR
ForEveR

Reputation: 55887

In C++

switch is selection-statement

n3376 6.4/1 and 6.4.2 is about switch

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

break is jump-statement

n3376 6.6.1/1

The break statement shall occur only in an iteration-statement or a switch statement and causes termination of the smallest enclosing iteration-statement or switch statement; control passes to the statement following the terminated statement, if any.

Upvotes: 12

Related Questions