C++ if statement

C++ Decision Making

aif statementConsists of a boolean expression followed by one or more statements.

Syntax

In C++ifThe syntax of the statement:

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

If the Boolean expression istrue, the code block within the if statement will be executed. If the boolean expression isfalse, the first set of code after the if statement ends (after the closing bracket) will be executed.

The C language treats anynon-zeroandnon-nullThe value is assumed to betrue, takezeroornullassumed to befalse。

Flowchart

C++ 中的 if 语句

Example

#include <iostream>
using namespace std;
 
int main ()
{
   // 局部变量声明
   int a = 10;
 
   // 使用 if 语句检查布尔条件
   if( a < 20 )
   {
       // 如果条件为真,则输出下面的语句
       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 的值是 10

C++ Decision Making

other extensions