Programming case/switch clarification

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.


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...

    case 1:
        // do something

    case 2:
        // do something else

        // nothing matched so do this

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.