C if ... else statement
After aif statement with an optional else statement,else statement executes the Boolean expression is false.
grammar
C language syntax ofif ... else statement:
if(boolean_expression) { /* 如果布尔表达式为真将执行的语句 */ } else { /* 如果布尔表达式为假将执行的语句 */ }
If the Boolean expression istrue, then the code ifthe execution block. If the Boolean expression isfalse, then the code within the elseblock executed.
C language to anynon-zero and non-nullvalue is assumed to betrue,thezeroornullassumed to befalse.
flow chart
Examples
#include <stdio.h> int main () { /* 局部变量定义 */ int a = 100; /* 检查布尔条件 */ if( a < 20 ) { /* 如果条件为真,则输出下面的语句 */ printf("a 小于 20\n" ); } else { /* 如果条件为假,则输出下面的语句 */ printf("a 大于 20\n" ); } printf("a 的值是 %d\n", a); return 0; }
When the above code is compiled and executed, it produces the following results:
a 大于 20 a 的值是 100
if ... else if ... else statement
After aif statement with an optional else if ... elsestatement, which can be used to test a variety of conditions.
When using if ... else if ... else statement, the following points should be noted:
- Available with a zero or after a if else, else must after all else if.
- If the latter can be followed by zero or more else if, else if necessary before else.
- Once a successful match else if, else if or else the other will not be tested.
grammar
C language syntax ofif ... else if ... else statement:
if(boolean_expression 1) { /* 当布尔表达式 1 为真时执行 */ } else if( boolean_expression 2) { /* 当布尔表达式 2 为真时执行 */ } else if( boolean_expression 3) { /* 当布尔表达式 3 为真时执行 */ } else { /* 当上面条件都不为真时执行 */ }
Examples
#include <stdio.h> int main () { /* 局部变量定义 */ int a = 100; /* 检查布尔条件 */ if( a == 10 ) { /* 如果 if 条件为真,则输出下面的语句 */ printf("a 的值是 10\n" ); } else if( a == 20 ) { /* 如果 else if 条件为真,则输出下面的语句 */ printf("a 的值是 20\n" ); } else if( a == 30 ) { /* 如果 else if 条件为真,则输出下面的语句 */ printf("a 的值是 30\n" ); } else { /* 如果上面条件都不为真,则输出下面的语句 */ printf("没有匹配的值\n" ); } printf("a 的准确值是 %d\n", a ); return 0; }
When the above code is compiled and executed, it produces the following results:
没有匹配的值 a 的准确值是 100