文章目录
Conditionals
Conditionals are used to perform different computations or actions depending on whether a condition evaluates to true or false.
The if statement is called a conditional control structure because it executes(执行) statements when an expression is true. For this reason, the if is also known as a decision structure. It takes the form:
if (expression)
statements
The expression evaluates to either true or false, and statements can be a single statement or a code block enclosed by curly braces { }.
Relational Operators(关系运算符)
Conditional Expressions(条件表达式)
Another way to form an if-else statement is by using the ?: operator in a conditional expression. The ?: operator can have only one statement associated with the if and the else.
Nested if Statements(嵌套 if 语句)
An if statement can include another if statement to form a nested statement. Nesting an if allows a decision to be based on further requirements.
Consider the following statement:
#include <stdio.h>
int main() {
int profit = 1400;
int clients = 18;
int bonus;
if (profit > 1000)
if (clients > 15)
bonus = 100;
else
bonus = 25;
printf("%d", bonus);
}
suggest explicit braces to avoid ambiguous ‘else’
Appropriately indenting nested statements will help clarify the meaning to a reader. However, be sure to understand that an else clause is associated with the closest if unless curly braces { } are used to change the association.
The if-else if Statement
When a decision among three or more actions is needed, the if-else if statement can be used.
There can be multiple else if clauses and the last else clause is optional.
Carefully consider the logic involved when developing an if-else if statement. Program flow branches to the statements associated with the first true expression and none of the remaining expressions will be tested.
Although ind