Explanation for the output of this function

I am doing survey questions that ask me: “What is the result of the following,” and I have some problems understanding something about this function:

int a = 1, b = 1, c = -1;
c = --a && b++;
printf("%d %d %d", a, b, c);

Exit 010. My question relates to Line 2 c = --a && b++. How is this line handled and how does it work / change values? And if it was c = --a || b++? In my opinion, I thought the output would be 020.

+4
source share
7 answers

(&& ||) - , , , , .

, --a 0 (= false), ... && ... , "false AND anything" false. , b++ , 1 .

--a || b++ ( "false OR something" ), b++ ( , b, ).

, , - pre-and post-increment/decment. -- ++ ( --a), , . ( b++) -- ++, , / .

, , --/++ (, a++ + ++a), , undefined - , , .

+11

c = --a && b++, a . --a && b++ - --- , --a==0 0 , ---, b .

a 0 b 1.

, , 0 1 0.

, c = --a || b++, a , --- , , , b++ 1 b. 0 2 1, c 0 || 1, 1.

,

+6

.

  • Postfix, C11, §6.5.2.4, ( )

    postfix ++ . [...] postfix -- postfix ++, , .

  • , C11, §6.5.3.1 ( )

    ++ . . [...] -- ++, , .

AND (&&). §6.5.13 ( , )

&& ; , . 0, . [...]

,

int a = 1, b = 1, c = -1;
c = --a && b++;

c = 0 && .....; // done..., a is decremented to 0, 
                //            so, LHS of && is 0, RHS is not evaluated,
                //            b remains 1
                //            and finally, C gets 0.

, (||) , , , § 6.5.5

[...] || ; , . 0, .

,

int a = 1, b = 1, c = -1;
c = --a || b++;

c = 0 || 1;   //yes, b value will be used, and then incremented.

,

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

0 2 1
+3

:

c = --a && b++;

a 0, 0 && anything else 0. a c 0, , .

, . a 0, && , , , 0. , b++ , b . 1 2 , , 0 1 0 0 2 0.

+1
c = --a && b++;

--a evaulated a 0, 1 && , b++ , b 1 c 0.

+1

b ++ , --a false an. , . , b , , , .

+1

- a: , a . b ++: b . c ( ) = 0 + 1 = 1; : a = 0, b = 2, c = 1; OK

-2

All Articles