Control Flow
Logical Operators
Here are some logical operators you can use in expressions:
Expression | True If… |
---|---|
expr1 == expr2 | expr1 is equal to expr2 |
expr1 != expr2 | expr1 is not equal to expr2 |
expr1 < expr2 | expr1 is less than expr2 |
expr1 <= expr2 | expr1 is less than or equal to expr2 |
expr1 > expr2 | expr1 is greater than expr2 |
expr1 >= expr2 | expr1 is greater than or equal to expr2 |
!expr | expr is false (i.e., zero) |
expr1 && expr2 | expr1 and expr2 are true |
expr1 || expr2 | expr1 or expr2 is true |
false && expr2
will always evaluate to false
, and true || expr2
will always evaluate to true
, regardless of what expr2
evaluates to.
This is called “short circuiting”: C evaluates the left-hand side of these expressions first and, if the truth value of that expression means that the other one doesn’t matter, it won’t evaluate the right-hand side at all.
Conditionals
Here is the syntax for if
/else
conditions:
if (condition) {
// code to execute if condition is true
} else if (another_condition) {
// code to execute if condition is false but another_condition is true
} else {
// code to execute otherwise
}
The else if
and else
parts are optional.
Switch/Case
A switch
statement can be a succinct alternative to a cascade of if
/else
s when you are checking several possibilities for one expression.
switch (expression) {
case constant1:
// code to execute if expression equals constant1
break;
case constant2:
// code to execute if expression equals constant2
break;
// ...
default:
// code to be executed if expression doesn't match any case
}
While Loop
while (condition) {
// code to execute as long as condition is true
}
For Loop
for (initialization; condition; increment) {
// code to execute for each iteration
}
Roughly speaking, this for
loop behaves the same way as this while
equivalent:
initialization;
while (condition) {
// code to execute for each iteration
increment;
}
break
and continue
To exit a loop early, use a break;
statement.
A break
statement jumps out of the innermost enclosing loop or switch statement.
If the break statement is inside nested contexts, then it exits only the most immediately enclosing one.
To skip the rest of a single iteration of a loop, but not cancel the loop entirely, use continue
.