C Conditionals: An Introduction to if/else and switch
Introduction
Conditional statements are fundamental in programming languages as they allow programmers to make choices based on the state of the data. In C, there are two primary ways to perform conditional statements: the if
statement, accompanied by the else
helper, and the switch
statement.
if Statement
The if
statement allows you to check a condition and execute a block of code enclosed in curly brackets if the condition is true. Here is an example:
1 | int a = 1; |
To handle the case when the condition is false, you can add an else
block:
1 | int a = 1; |
It’s important to use the comparison operator ==
in comparisons instead of the assignment operator =
. Using the assignment operator in the condition will result in the conditional check always being true, except when the argument is 0
. For example:
1 | int a = 0; |
In this case, the condition a = 0
will be true because assignment returns the assigned value, which is 0
in this case.
Multiple else
blocks can be achieved by stacking multiple if
statements:
1 | int a = 1; |
switch Statement
The switch
statement is useful when multiple if
statements are required to check the exact value of a variable. Instead of stacking if
statements, the switch
statement can provide a more concise solution. Each expected value can be associated with a case
entry point:
1 | int a = 1; |
For each case
, we need to include a break
statement at the end to prevent the execution of the next case
block when the preceding one ends. However, the “cascade” effect can be utilized creatively in certain scenarios.
A “catch-all” case labeled as default
can be added at the end to handle all other cases:
1 | int a = 1; |
Tags: C programming, conditionals, if/else, switch