Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is switch case a loop or a conditional construct?

Tags:

c++

c

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

  • It executes once, unlike a loop which has the capability to execute multiple times.
  • There is no loop control mechanisms, there is only conditional switching based on different cases.

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.

like image 810
CodeCrusader Avatar asked Dec 05 '22 11:12

CodeCrusader


1 Answers

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.

like image 68
ForEveR Avatar answered Dec 22 '22 09:12

ForEveR