Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

c - Shortcircuiting of AND in case of increment / decrement operator

In the code below:

#include <stdio.h>

int main()
{
     int a = 1;
     int b = 1;
     int c = a || --b;
     int d = a-- && --b;
     printf("a = %d, b = %d, c = %d, d = %d", a, b, c, d);
     return 0;
}

i was expecting the output to be:

a=0,b=1,c=1,d=0

because due to short circuiting in the line below, ie a-- returns 0 so the other part wont get executed right?

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

The output is:

a = 0, b = 0, c = 1, d = 0

can anyone please explain?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...