简体   繁体   中英

Why does the value of c not change?

#include <stdio.h>
void main()
{
    int a = 5, b = -7, c = 0, d;
    d = ++a && ++b || ++c;
    printf("\n %d,%d,%d,%d", a,  b, c, d);
}

In the above code, the output is 6,-6,0,1. Why is the value of c 0 and the value of d 1? how did d get the value as 1?

That is because || first checks the left part and if it is true it return true without evaluating the right part.

In C any non zero is treated as True and zero as False

int a = 5, b = -7, c = 0, d;
    d = ++a && ++b || ++c;

Here ++a and ++b are non zero and both are treated as True so ++a&&++b becomes True and the expression stops evaluating over there.

There are already good answers that explain why c is 0 after the line

d = ++a && ++b || ++c;

is executed.

The line is equivalent to:

d = (++a && ++b || ++c);

That explains why d is 1 .

int a = 5, b = -7, c = 0, d;
d = ++a && ++b || ++c;

let's analyze the statement part by part

++a : a=6

++a && ++b: b becomes -6 ,and then it does : 6 && -6 ,which is equal to 1

now there is a || (or symbol) ,but this cannot affect the value of d since

1||"value2" =1 , so the compiler does not evaluate "++c" .

so c remains 0 and d becomes 6 && -6 =1

&& has higher precedence than || so first ++a&&++b is evaluated first and it becomes true. The expression becomes true || ++c true || ++c and || will evaluate from left to right since || encounters true and it returns 1 to d without evaluating ++c. So c value will not be incremented

An evaluation tree is created which does the evaluation. The || part is parent and the two parts on its side are its parents. When it evaluates one child, if it gets true, it doesn't evaluate the other child.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM