Swich Statement in C
switch
statement is a control structure used for making decisions based on the value of a variable or expression. It allows you to test a variable against a list of values (cases) and execute a block of code associated with the first matching case. Here's how the switch
statement works:
1. The
switch
keyword is followed by an expression (usually a variable) enclosed in parentheses. This expression is evaluated to determine which case to execute.2. Inside the
switch
block, you list one or morecase
labels. Eachcase
label represents a possible value that the expression might have.3. When the
switch
statement is executed, it compares the value of the expression to eachcase
constant sequentially.4. If a match is found (i.e., if the expression's value is equal to a
case
constant), the code block associated with thatcase
is executed.5. The
break
statement is used to exit theswitch
block. Withoutbreak
, the execution would continue into subsequentcase
blocks until abreak
is encountered or theswitch
block ends.6. If none of the
case
values matches the expression, thedefault
block is executed (if it exists). Thedefault
block is optional and serves as a fallback.
switch
statement:
switch (expression) {
case constant 1:
// Code to be executed if expression equals constant 1
break;
case constant 2:
// Code to be executed if expression equals constant 2
break;
default:
// Code to be executed if no case matches
}
In this example, the user enters a number, and the switch
statement determines which option was chosen based on the input value. If the input doesn't match any of the cases, the default
block is executed.