Shortcircuiting of AND in case of increment / decrement operator

孤街浪徒 提交于 2019-11-29 16:03:39
int c = a || --b;

In this line, the C standard requires the C implementation to evaluate a first and, if it is not zero, not to evaluate --b. Although -- has higher precedence than ||, that just means that -- is grouped with b for the purposes of determining the structure of the expression, not for purposes of evaluating it. The left side of an || operator must be evaluated before the right side and, if the left side is true, the right side must not be evaluated, even in part.

So, after the above, b is not changed; it is still 1.

int d = a-- && --b;

As with ||, the left-hand side of the && is evaluated first. So a-- is evaluated. This changes a to 0. However, the value of a-- is a before the change, so it is 1. A value of 0 would prevent the right side from being evaluated (because, once we know the left side is zero, we know the value of the complete && expression is zero). But, since the left side is not zero, --b must be evaluated to finish the &&. This changes b to 0. “Short-circuiting” means the left side is evaluated first, but the right side is still evaluated when necessary.

In first case

int c = a || --b;  

After this a=1 , b=1 and c=1

a value is 1 , because of short circuit evaluation --b did not performed

int d = a-- && --b;

a-- is post decrement so decrement of a won't effect in expression where as --b is pre decrement so effects here

Your condition becomes

   int d= 1 && 0 ; 

After this a=0; , b=0,c=1 and d=0.

In the first or operation, --b is not executed since a equals 1:

int c = a || --b;

But b is decremented here:

int d = a-- && --b;

Because a equals 1 and is decremented after it is evaluated (a-- equals 1). In other words, this line is similar to:

int d = 1 && --b;

b was equal to 1 so now b equals 0 now. And d also equals 0 because --b returns 0.

the line below, ie a-- returns 0

No, it doesn't. It yields 1, as the post-decrement operator evaluates to the unmodified value of the variable. What you are thinking about is perhaps --a.

niko

c = a || --b

so at first a is evaluated and a value is 1 which is true. So compiler does not evaluate --b. So b value is still 1

Now

d = a-- && --b

a-- && --b => 1 && 0 (since --b = 0 ) since b value is at 1.

why 1 because a-- is post decrement operator

Why 0 because --b is pre decrement operator

so 1 && 0 returns 0 and this value is stored in d

So the output: a = 0, b = 0, c = 1, d = 0

You're mixing up a-- with --a. The result of the expression a-- is a before the decrement, while --a is a after the decrement; in other words:

int a = 1;
int b = a--; // b == a == 1
int c = --b; // c == b-1 == 0

As a result, you have:

int d = a-- && --b;
// =>   1   && b-1
// =>   1   && 0
// =>   0
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!