ChatGPT解决这个技术问题 Extra ChatGPT

Why does this if-statement combining assignment and an equality check return true?

I've been thinking of some beginner mistakes and I ended up with the one on the if statement. I expanded a bit the code to this:

int i = 0;
if (i = 1 && i == 0) {
    std::cout << i;
}

I have seen that the if statement returns true, and it cout's i as 1. If i is assigned 1 in the if statement, why did i == 0 return true?

Guys, this is not a typo question. The OP wants to know why the if statement is entered with this code since i is set to 1.
Or does it assign the result of 1 && i == 0?
Suggestion for beginners: They should not use such "advanced" language construct. Just assign the variable separately. That will also avoid possible problems with sequence point. This kind of code in practical code will usually looks bad too.
this is bound to end up on an interview question

s
syck

This has to do with operator precedence.

if (i = 1 && i == 0)

is not

if ((i = 1) && (i == 0))

because both && and == have a higher precedence than =. What it really works out to is

if (i = (1 && (i == 0)))

which assigns the result of 1 && (i == 0) to i. So, if i starts at 0 then i == 0 is true, so 1 && true is true (or 1), and then i gets set to 1. Then since 1 is true, you enter the if block and print the value you assigned to i.


@JörgWMittag That's pretty cool. I like that it forces you to use parentheses.
Basically, i = !i; if (i) properly written
@NathanOliver: Fortress was a pretty cool language that got a lot of things right. (The lead designer was Guy L. Steele, so no surprise there.) Unfortunately, it didn't get picked up for the final round of DARPA funding, and was subsequently mothballed by Oracle.
Naturally, asking for a modicum of warnings from the compiler would have detected that error,
Any language that doesn't assume ints and booleans are equivalent would also pick this up.
佚名

Assuming your code actually looks like this:

#include <iostream>
using namespace std;

int main()  {
    int i = 0;
    if (i = 1 && i == 0) {
        cout << i;
    }
}

Then this:

if (i = 1 && i == 0) {

evaluates as

 if (i = (1 && i == 0)) {

and so i is set to 1.


Was the extra code really necessary? It seems pretty obvious that this would be the case as it would not run otherwise.
Not only unnecessary extra code. The answer fails to clearly explain operator precedence.
Since we're on the nitpick train... I see a using namespace std!
There is extra code - but it is still not incorrect code. And the answer is still right. Of course, it does not explain operator precedence. But someone could suggest it to be added, instead of outright down-voting!
Wow, -4 is harsh, considering this answers the question correctly, though maybe not optimally. It doesn't expand on operator precedence as much as the other answer, but it does say just enough about it in the context of the code so that anyone who thought that = came before && can see the issue. Also, yes, the expansion is extraneous, but I don't think it matters that much. I can't believe such minor differences cause people to vote 151 to -4.
a
ar18

The actual answer is:

The compiler gives precedence to "i == 0", which evaluates to true. Then it will evaluate i=1 as TRUE or FALSE, and since compiled assignment operators never fail (otherwise they wouldn't compile), it also evaluates to true. Since both statements evaluate as true, and TRUE && TRUE evaluates to TRUE, the if statement will evaluate to TRUE.

As proof, just look at the asm output of your compiler for the code you entered (all comments are my own):

mov     dword ptr [rbp - 8], 0    ; i = 0;
cmp     dword ptr [rbp - 8], 0    ; i == 0?
sete    al                        ; TRUE (=1)
mov     cl, al
and     cl, 1                     ; = operator always TRUE
movzx   edx, cl
mov     dword ptr [rbp - 8], edx  ; set i=TRUE;
test    al, 1                     ; al never changed,
                                  ; so final ans is TRUE

The asm output above was from CLANG, but all other compilers I looked at gave similar output. This is true for all the compilers on that site, whether they are pure C or C++ compilers, all without any pragmas to change the mode of the compiler (which by default is C++ for the C++ compilers)

Note that your compiler did not actually set i=1, but i=TRUE (which means any 32-bit not zero integer value). That's because the && operator only evaluates whether a statement is TRUE or FALSE, and then sets the results according to that result. As proof, try changing i=1 to i=2 and you can observe for yourself that nothing will change. See for yourself using any online compiler at Compiler Explorer


1) The docs link to C operator precedence, when this question is tagged with C++. Two different languages. 2a) i = 1 is an assignment [not an equivalence] operator; 2b) I can assure you that if (i = 0) will evaluate to false condition in both C and C++, so whether it evaluates to true wrt "it never fails" is somewhat misleading.
and cl, 1 ; = operator always TRUE << correct me if I am wrong, but I see no assignation here. It represents the 1 && part of the expression. So this answer basically evaluates to false.
"The docs link to C operator precedence, when this question is tagged with C++. Two different languages" -- and when you compare C to C++ operator precedence, what is the difference between the two? They have the same precedence in regards to this topic, which isn't surprising, seeing as C++ is a direct derivative of C (or another way to put it is, C is a subset of the C++ language, so of course they will have a lot in common, including precedence). I will fix my post anyways, in case that is confusing.
"Correct me if I am wrong, but I see no assignation here" -- Then let me correct you! The 1 is an immediate value and not the result of any test or calculation. It is what is called a "presumed TRUE" value. The only test that takes place is for the i==0 statement, i.e. -- "cmp dword ptr [rbp - 8], 0". You would only be correct if it had said "movzx edx,1". According to ALL the posts preceding mine, there should be two comparisons, but in real life there is only one, and the asm output of EVERY major compiler proves those posts are completely incorrect.
As well as getting the precedence wrong (see NathanOliver's answer for the correct parsing), you make the false claim that the assignment operator always evalutes to TRUE. Try if ( i = 0 ) { print something }. Also your answer contradicts itself; at the start you say that i=1 is evaluated before && is applied, and then at the end you say that i is set to the result of the && operator.
L
Leslie Satenstein

It has to do with parsing an the right to left rules. Eg y = x+5. All sub-expressions are weighted in importance. Two expressions of equal importance are evaluated right to left, . The && expression side is done first, followed by the LHS.

Makes sense to me.


Associativity ("right to left rules") has nothing to do with this. It's about precedence ("importance"), and the operators used don't have equal precedence.