0

i have just started c++ programming.i get the following code in my CS exam.i just want to know how this code is working because i thought if statement is used to check condition.

`int a=0,b=0;
if(a++&&b++)
cout<<"A="<<a<<"\nB="<<b;
else
cout<<"B="<<b<<"\nA="<<a;`

here is the output

  • 1
    `a++` evaluates to `0`, so with the `&&`, the `b++` isn't taken. So the condition is `false`, and `A` is now `1` and `B` stays `0`. – Blaze Feb 04 '20 at 13:51
  • TL;DR of the dupe: This is called short circuit evaluation. If the first part of an and expression is false, there is no other result than false so the rest of the expression is not evaluated. – NathanOliver Feb 04 '20 at 13:52
  • The postfix increment (and decrement) returns the *old* value, before the increment (or decrement). So if `a` is initialized to `0`, then e.g. `int t = a++;` will initialize `t` to `0` while `a` is incremented to `1`. And `0` is equivalent to `false`. And due to the short-circuit nature of `&&`, the expression `a++ && b++` will be equivalent to `0 && b++` which is equivalent to plain `0` which as mentioned is `false`. – Some programmer dude Feb 04 '20 at 13:53
  • Welcome to Stack Overflow. Please look at our [https://stackoverflow.com/help](intro pages). Don't post a link to the output, post the actual output. Not a screenshot, but text. Also, I understand that English may not be your first language, but I'm sure you know that you should capitalize the first letter of each sentence, and put a space between the end of one sentence and the beginning of the next; please do us the courtesy of following these rules, as it makes your question easier to read. – Beta Feb 04 '20 at 13:55

0 Answers0