操作员评估

Operators evaluation

本文关键字:评估 操作员      更新时间:2023-10-16

此代码评估为true:

#include <iostream>

int main(){
 int x = 9;
 int j = x-1;
 if(x - j+1 > 1)
  std::cout << "Ehhhh???n";
}

但这个是假的:

#include <iostream>
int main(){
 int x = 9;
 int j = x-1;
 if(x - (j+1) > 1)
  std::cout << "Ehhhh???n";
}

正负运算符的优先级高于"<",我也只使用一种数据类型,所以应该有bo溢出。为什么结果不同?

这实际上只是一个加1到什么值的问题。加法和减法具有从左到右的关联性,所以我们从左开始,向右进行。

x - j + 1
(9 - 8) + 1
1 + 1
2

作为

x - (j + 1)
9 - (8 + 1)
9 - 9
0

强制将加法附加到j而不是x-j,因此第二种情况正确地为false。

由于算术+和-的优先级相同,但结合性是从左到右,因此没有括号的将首先进行减法,然后进行加法,即:

x - j+1 ==2 //here the operation is performed from left to right,subtraction first then addition
x - (j+1)==0 //here the one inside the parenthesis will be done first,i.e addition first then subtraction

数学上有两个不同的表达式:

x - j + 1 is equal to  x - ( j - 1 )

x - ( j + 1 ) is equal to x - j - 1