Why do we have to use break in switch
Posted
by
trejder
on Programmers
See other posts from Programmers
or by trejder
Published on 2012-08-28T09:16:34Z
Indexed on
2012/08/28
9:50 UTC
Read the original article
Hit count: 275
conditions
Who decided, and basing on what concepts, that switch
construction (in many languages) has to be, like it is? Why do we have to use break
in each statement? Why do we have to write something like this:
switch(a)
{
case 1:
result = 'one';
break;
case 2:
result = 'two';
break;
default:
result = 'not determined';
break;
}
I've noticed this construction in PHP and JS, but there are probably many other languages that uses it.
If switch
is an alternative of if
, why we can't use the same construction for switch
, as for if
? I.e.:
switch(a)
{
case 1:
{
result = 'one';
}
case 2:
{
result = 'two';
}
default:
{
result = 'not determined';
}
}
It is said, that break
prevents execution of a blocks following current one. But, does someone really run into situation, where there was any need for execution of current block and following ones? I didn't. For me, break
is always there. In every block. In every code.
© Programmers or respective owner