What does the switch
statement do in C?
a) Selects one of many code blocks to execute
b) Declares a loop
c) Defines a variable
d) Terminates a program
Answer:
a) Selects one of many code blocks to execute
Explanation:
The switch
statement in C allows a variable to be tested for equality against a list of values. Each value is known as a case, and the variable being evaluated is compared to each case. If a match is found, the block of code associated with that case is executed. If no match is found, an optional default
case can be executed.
Switch
statements are particularly useful when you need to select one of many possible actions based on the value of a single variable. This structure is often more readable and efficient than a series of if-else
statements.