C/C++ 语言中的 if...else if...else 语句
1. if
statement
The syntax of the if
statement is:
if (condition) {
// body of if statement
}
The code inside { }
is the body of the if
statement.
If the condition
evaluates to true
, the code inside the body of if
is executed.
If the condition
evaluates to false
, the code inside the body of if
is skipped.
2. if...else
statement
If the boolean expression evaluates to true
, then the if
block of code will be executed, otherwise else
block of code will be executed.
if(boolean_expression) {
// statement(s) will execute if the boolean expression is true
} else {
// statement(s) will execute if the boolean expression is false
}
If the condition
evaluates true
,
the code inside the body of if
is executed
the code inside the body of else
is skipped from execution
If the condition
evaluates false
,
the code inside the body of else
is executed
the code inside the body of if
is skipped from execution
3. if...else if...else
statement
The syntax of the if...else if...else
statement is:
if (condition1) {
// code block 1
}
else if (condition2){
// code block 2
}
else {
// code block 3
}
If condition1
evaluates to true
, the code block 1
is executed.
If condition1
evaluates to false
, then condition2
is evaluated.
If condition2
is true, the code block 2
is executed.
If condition2
is false, the code block 3
is executed.
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
References
[1] Yongqiang Cheng, https://yongqiang.blog.csdn.net/
[2] C++ if, if…else and Nested if…else, https://www.programiz.com/cpp-programming/if-else