If conditions & switch
if true, do A, otherwise, do B
Selection Statements
Selection statements modify the control flow of the program. It uses different sets of code depending on the condition at runtime.
If Statements
Code blocks are bounded by a set of {}
, which you have already seen, surrounds the main()
function.
The if statements take the following formats:
if (<expression>) <statement_true>
if (<expression>) <statement_true> else <statement_false>
If expression
evaluates to a non-zero
value, then statement_true
is evaluated. Otherwise, statement_false
is evaluated if provided along with the else
clause.
Often, statement_false
is itself another if statement, chaining into an (if, else if, else) structure.
The following is an example:
At the beginning, the value of money is 100. When the program is executing the first if statement, money
is a non-zero value, so printf("I have $%d.\n", money);
is executed.
The value of money
is then substracted by 100, so the value is now equal to 0
. Then when the program runs the second if
statement, the if-block is skipped.
We can chain multiple if-conditions by writing another if-statement after an else
.
The following is an example:
Switch Statements
Switch statements allow a variable to be tested for each case. It contains jump statements and labels, which we do not recommend using outside of switch statements. They act simply as alternatives to if statements on the superficial level. The format is as follows:
switch (<expression>) <statement>
The "expression" here must evaluate to some integral value. The "statement" here is typically a block with case labels.
case <integer_constant_expression>: <statement>
default: <statement>
Each case is compared against the expression in the switch parenthesis, if a match is found, the program jumps to that case and starts executing line by line, and only exits when encountering break;
or when the code block ends.
Basically, switch-statements are just if-statements when all their conditions are x == case
.
Last updated