Conditional Statements
Conditional statements control conditional branching. The body of a conditional statement is only executed if the value of the expression is nonzero.
If Statement
Syntax
if-statement
:
if (
expression
)
statement
if (
expression
)
statement
else
statement
Example
int a = 1;
if (a < 0) {
a = 0;
} else {
a++;
}
In this example, if a
is a negative number, its value is set to zero. Otherwise, the value of a
is increased by 1.
You can also have nested branching, like so:
int a = 0;
int b = 0;
if (a > 0) {
if (b > a) {
a = b;
}
} else {
b = a;
}
Or concurrent if statements:
int a = 1;
if (a < 0) {
a = -1;
} else if (a > 1) {
a = 1;
} else {
a = 0;
}
Last updated