Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C++ if Statement

C++ if Statement

C++ Decision C++ Decision Making

A if statement if statement consists of a Boolean expression followed by one or more statements.

Syntax

In C++ if statement syntax:



if(boolean_expression)

{

   // statement to execute if the boolean expression is true

}

If the Boolean expression is true, then the code block inside the if statement is executed. If the Boolean expression is false, then the first set of code after the if statement ends (after the closing brace) is executed.

C treats anynon-zeroandnon-nullvalue as true, and treatszeroor null as false.

Flowchart

Example



#include 

using namespace std;

 

int main ()

{

   // Local variable declaration

   int a = 10;

 

   // Use an if statement to check a boolean condition

   if( a < 20 )

   {

       // 如果条件为真,则输出下面的语句

       cout << "a 小于 20" << endl;

   }

   cout << "a 的值是 " << a << endl;

 

   return 0;

}

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



a 小于 20

a 的值是 10

C++ Decision C++ Decision Making