操作员评估
Operators evaluation
此代码评估为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
相关文章:
- std::condition_variable::wait()如何评估给定的谓词
- <<操作员在下面的行中工作
- c++11评估顺序(未定义的行为)
- C++ 与操作员不匹配<<
- 操作员C++的模棱两可的过载
- C++中>>操作员过载时出现问题?
- NaN 上的宇宙飞船操作员
- 如何使用"equal to"以外的评估编写开关语句
- 嵌套 if 中没有返回评估
- 懒惰的参数评估try_emplace?
- 在实践中,在运行时为零的乘法中是否有任何"lazy"评估
- 比根<操作员
- SFINAE不能防止模棱两可的操作员过载吗?
- C++操作员订单评估
- C const char *评估操作员超载
- C 评估表达操作员优先级不起作用
- XOR操作员未在C 中正确评估
- 操作员评估
- 操作员评估指令后
- 停止评估操作员<<