C++ if...else statement

C++ Decision Making

aif statementcan be followed by an optionalelse statement, the else statement executes when the boolean expression is false.

Syntax

In C++if...elseSyntax of the statement:

if(boolean_expression)
{
   // 如果布尔表达式为真将执行的语句
}
else
{
   // 如果布尔表达式为假将执行的语句
}

If the boolean expression istrue, then executeifcode within the block. If the boolean expression isfalse, then executeelseCode within the block.

Flowchart

C++ 中的 if...else 语句

Example

#include <iostream>
using namespace std;
 
int main ()
{
   // 局部变量声明
   int a = 100;
 
   // 检查布尔条件
   if( a < 20 )
   {
       // 如果条件为真,则输出下面的语句
       cout << "a 小于 20" << endl;
   }
   else
   {
       // 如果条件为假,则输出下面的语句
       cout << "a 大于 20" << endl;
   }
   cout << "a 的值是 " << a << endl;
 
   return 0;
}

When the above code is compiled and executed, it produces the following result:

a 大于 20
a 的值是 100

if...else if...else statement

aifThe statement can be followed by an optionalelse if...elsestatement, which can be used to test multiple conditions.

When using if...else if...else statements, the following points need attention:

  • An if can be followed by zero or one else, and the else must come after all else ifs.
  • An `if` can be followed by zero or more `else if` statements, and the `else if` must come before `else`.
  • Once an else if matches successfully, the other else ifs or else will not be tested.

Syntax

In C++if...else if...elseSyntax of the statement:

if(boolean_expression 1)
{
   // 当布尔表达式 1 为真时执行
}
else if( boolean_expression 2)
{
   // 当布尔表达式 2 为真时执行
}
else if( boolean_expression 3)
{
   // 当布尔表达式 3 为真时执行
}
else 
{
   // 当上面条件都不为真时执行
}

Example

#include <iostream>
using namespace std;
 
int main ()
{
   // 局部变量声明
   int a = 100;
 
   // 检查布尔条件
   if( a == 10 )
   {
       // 如果 if 条件为真,则输出下面的语句
       cout << "a 的值是 10" << endl;
   }
   else if( a == 20 )
   {
       // 如果 else if 条件为真,则输出下面的语句
       cout << "a 的值是 20" << endl;
   }
   else if( a == 30 )
   {
       // 如果 else if 条件为真,则输出下面的语句
       cout << "a 的值是 30" << endl;
   }
   else
   {
       // 如果上面条件都不为真,则输出下面的语句
       cout << "没有匹配的值" << endl;
   }
   cout << "a 的准确值是 " << a << endl;
 
   return 0;
}

When the above code is compiled and executed, it produces the following result:

没有匹配的值
a 的准确值是 100

C++ Decision Making

other extensions