C || Variable value is strange after logical expression.

Asked 2 weeks ago, Updated 2 weeks ago, 2 views

#include<stdio.h>
int main()
{
    int a,b,c;
    a=1;
    b=2;
    c=3;
    printf("%d",(a=b)||(b=c));
    printf("%d",b);

}

Here, when a and b and c are output as a=2,b=2,c=3, b goes in b and b goes in Isn't it right to output as a=2,b=3,c=3? Please tell me where the problem is

c

2022-09-20 15:38

1 Answers

    printf("%d",(a=b)||(b=c));

We're only going to do a=b here, and we're not going to do b=c.

When evaluating the logic expression condA ||condB, if condA is true, condB is the entire expression true. Since a=b was evaluated as true, b=c is not done.

on the contrary If there is a logic expression condA &&condB and condA is true, we will evaluate it up to condB to see if the next logic expression is also true. So in the code, this part

    printf("%d",(a=b)&&(b=c));

If you switch to and run it, you'll see that the last result of the a, b, c variable is different.


2022-09-20 15:38

If you have any answers or tips


© 2022 pinfo. All rights reserved.