
上QQ阅读APP看书,第一时间看更新
5.3 关系运算符和关系表达式
关系运算也叫比较运算,用来比较两个表达式的大小关系。所以关系运算符用于各种比较运算,包括大于(>)、小于(<)、等于(=)、大于等于(>=)、小于等于(<=)和不等于(!=)6种,关系运算符表达式的值是“真”和“假”,用“1”和“0”来表示。
5.3.1 关系运算符

表5-5显示了C++支持的关系运算符。
表5-5 关系运算符

在6个关系运算符中<、<=、>、>=的优先级相同,高于==和!=,==和!=的优先级相同。关系运算符的优先级低于算术运算符,高于赋值运算符。关系运算符都是双目运算符,其结合性均为左结合。
5.3.2 关系表达式

【例5-5】编写程序,使用关系运算符对两个整型进行比较。
(1)在Visual Studio 2017中,新建名称为“5-5.cpp”的Project5文件。
(2)在代码编辑区域输入以下代码。

【程序分析】本程序中,定义了3个整型变量A、B、C,并分别给A、B赋初值5、10,利用关系运算符对两个整型变量进行比较,然后改变A和B的值,再次进行比较。
在Visual Studio 2017中的运行结果如图5-6所示。

图5-6 关系运算