If-statemenet condition
If-statemenet condition
本文关键字:condition If-statemenet 更新时间:2023-10-16
我很难理解这段代码的作用:
#include <iostream>
using namespace std;
int main()
{
int x = 0, y = 0;
if (x++ && y++)
y += 2;
cout << x + y << endl;
return 0;
}
输出为 1 x C++。但我认为应该是2?
为什么?因为在 if 语句的 () 中,我认为应该只检查它是否为真/假,因此它不会增加/减少任何整数。由于默认情况下这是真的,因此它为 2 增加 y?输出应该是 0+2 = 2,但它只输出 1?
if (x++ && y++)
不会做y++
,因为逻辑和运算符(&&
)左侧的条件是false
的,因为x++
将返回0
并将x
递增1。
由于false && expression
将为任何表达式生成 false,因此无需计算其余表达式。
因此,您最终会得到 x = 1
和 y = 0
.
这称为短路评估。
后++
算子具有高优先级,&&
算子可以进行短路评估。if (x++ && y++)
中发生的事情是,首先它评估x++
。结果为 0 并递增 x。由于 0 是假的 &&&会短路y++
的评估(不会被执行)。此外,if 将计算为 false,并且不会执行y+=2
。
所以现在你有x=1
和y=0
.
所以结果是 1。
它将首先执行x++
,编译器知道因此表达式x++ && y++
将为假,并将忽略y++
结果之后 x = 1 和 y = 0;
它与写if(false && do_something())
相同,在这种情况下,do_something()
永远不会被调用。
我建议你看看运算符优先级表: http://en.cppreference.com/w/cpp/language/operator_precedence
//in a statement, x++ will evaluate x then increment it by 1.
//in a statement, ++x will increment x by 1 then evaluate it.
如果您很难理解它,请尝试以下代码以更好地理解:
#include <iostream>
using namespace std;
int main()
{
int x = 0, y = 0;
if (++x && ++y) // in your case, with the previous code, it gives (0 && 0)
// instead of if statement you can try the following : cout << x++; then cout << ++x;
// and notice the difference
y += 2;
cout << x + y << endl;
return 0;
}
相关文章:
- 我的简单if-else语句是如何无法访问的代码
- 如何将enable-if与模板参数和参数包一起使用
- 无论条件是否为true,if总是在c++中执行
- Arduino:for/while/if在void setup()或void loop()之前?——错误:之前需要不合格
- Insert函数不适用于2 if语句C++
- If语句未被求值C++
- C++嵌套if语句,基本货币交换
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 是否可以使用if constexpr删除控制流语句
- 要与"if constexpr"一起使用的编译时消息(在预处理器之后)
- 如何删除peer if else分支中的冗长句子
- 我似乎对if/else的基本语句有问题:/
- if数组上的随机数
- 将按位if条件转换为普通if条件
- If语句在c++中被忽略
- 比较if语句中的数组值和int值
- 使用if-else将数字转换为单词
- 为什么简单的算术减法在"if"条件下不起作用?
- IF ELSE CONDITION
- If-statemenet condition