Can someone please explain how cases ans switches work in programming. I seen them numerous times in programming examples and they seem significant but I do not understand them.
Thanks
Can someone please explain how cases ans switches work in programming. I seen them numerous times in programming examples and they seem significant but I do not understand them.
Thanks
It’s a form of control flow statement. K&R defines it as “a special multi-way decision maker that tests whether an expression matches one of a number of constants”. There are some examples of it’s use in this thread.
int x;
// x is set to a value by some other code...
switch(x)
{
case 1:
// do something
break;
case 2:
// do something else
break;
default:
// nothing matched so do this
break;
}
this part
switch( x )
compares “x” to all the different cases, if a case matches then execution starts at that point. default is executed if none of the defined cases match. The break statement causes an immediate exit from the switch.