C++ if 语句
if 语句由一个布尔表达式后跟一个或多个语句组成。
语法
C++ 中 if 语句的语法如下 −
if(boolean_expression) {
// 如果布尔表达式为 true,则执行 statement(s)
}
如果布尔表达式求值为 true,则执行 if 语句内的代码块。如果布尔表达式求值为 false,则执行 if 语句结束处(右大括号之后)的第一组代码。
流程图
示例
#include <iostream>
using namespace std;
int main () {
// 局部变量声明:
int a = 10;
// 检查布尔条件
if( a < 20 ) {
// 如果条件为 true,则打印以下内容
cout << "a is less than 20;" << endl;
}
cout << "value of a is : " << a << endl;
return 0;
}
上述代码编译并执行后,将产生以下结果 −
a is less than 20; value of a is : 10