琐碎的话题,作业是否返回"假"?

Trivial topic, does an assignment return 'false'?

本文关键字:返回 是否 作业 话题      更新时间:2023-10-16

在这里,结果是6。但是i=5不是一个非零值吗?如果我输入I +=5,它就会认为它为真。这有什么不同?(也不,我不是故意把I ==5)

int i=7;
if(i=5) {
cout << ++i;
} else {
cout << --i;
}

=+=这样的赋值操作符返回对象被赋值后的值。所以,如果你赋值false0,你可以从赋值操作符中得到false

i=5计算为5,即if ()眼中的true。但是i=0会被计算为0,而if ()会被认为是false

赋值返回所赋的值。在您的示例中:

int i = 7;
if (i = 5) { // returns 5, which is non-zero, or "true"
    cout << ++i; // prints 6, or 5+1
}  else {
    cout << --i; // would print 4, or 5-1, if it was hit, which it never will
}

您可能会对前递增和后递增感到困惑。例如,考虑以下内容:

int i = 7;
if (i = 5) { // returns 5, which is non-zero, or "true"
    cout << i++; // prints 5, i is 6 after this line
}  else {
    cout << i--; // would print 5, but i is 4 after this line
}

你的代码是这样的:

i = 7;
i = 5;
if ( 5 ) // it's true. Isn't it ?
{
    i = i + 1; // now i is 6
    cout << i;
}