if 语句 (C)if Statement (C)

if 语句控制条件分支。The if statement controls conditional branching. 如果表达式的值不为零,则执行 if 语句体。The body of an if statement is executed if the value of the expression is nonzero. if 语句的语法有两种形式。The syntax for the if statement has two forms.

语法Syntax

selection-statement:selection-statement:
if ( expression ) statementif ( expression ) statement

if ( expression ) statement else statementif ( expression ) statement else statement

在两种形式的 if 语句中,将计算可具有结构之外的任何值的表达式(包括所有副作用)。In both forms of the if statement, the expressions, which can have any value except a structure, are evaluated, including all side effects.

在第一种形式的语法中,如果 expression 为 true(非零),则执行 statement。In the first form of the syntax, if expression is true (nonzero), statement is executed. 如果 expression 为 false,则忽略 statement。If expression is false, statement is ignored. 在第二种形式的语法(使用了 else)中,如果 expression 为 false,则执行第二个 statement。In the second form of syntax, which uses else, the second statement is executed if expression is false. 对于这两种形式,除非其中一个语句包含 break、continue 或 goto,否则控制随后会从程序中的 if 语句传递到的下一语句。With both forms, control then passes from the if statement to the next statement in the program unless one of the statements contains a break, continue, or goto.

下面是 if 语句的示例:The following are examples of the if statement:

if ( i > 0 )  
    y = x / i;  
else   
{  
    x = i;  
    y = f( x );  
}  

在此示例中,如果 y = x/i; 大于 0,则执行 i 语句。In this example, the statement y = x/i; is executed if i is greater than 0. 如果 i 小于或等于 0,则将 i 赋给 x,并将 f( x ) 赋给 yIf i is less than or equal to 0, i is assigned to x and f( x ) is assigned to y. 请注意,构成 if 子句的语句将以分号结尾。Note that the statement forming the if clause ends with a semicolon.

嵌套 if 语句和 else 子句时,请使用大括号将语句和子句分组到可阐名你的意图的复合语句中。When nesting if statements and else clauses, use braces to group the statements and clauses into compound statements that clarify your intent. 如果大括号不存在,则编译器会通过将每个 else 与没有 else 的最近的 if 关联来解决二义性。If no braces are present, the compiler resolves ambiguities by associating each else with the closest if that lacks an else.

if ( i > 0 )           /* Without braces */  
    if ( j > i )  
        x = j;  
    else  
        x = i;  

在本示例中,else 子句与内部 if 语句关联。The else clause is associated with the inner if statement in this example. 如果 i 小于或等于 0,则不会将任何值赋给 xIf i is less than or equal to 0, no value is assigned to x.

if ( i > 0 )   
{                      /* With braces */  
    if ( j > i )  
        x = j;  
}  
else  
    x = i;  

此示例中的内部 if 语句两边的大括号使 else 子句成为外部 if 语句的一部分。The braces surrounding the inner if statement in this example make the else clause part of the outer if statement. 如果 i 小于或等于 0,则将 i 赋给 xIf i is less than or equal to 0, i is assigned to x.

另请参阅See Also

if-else 语句 (C++)if-else Statement (C++)