Can anyone explain this "m" answer? Ans is -2,2,0,1 | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Can anyone explain this "m" answer? Ans is -2,2,0,1

What will be the output of the program? #include int main() { int i=-3, j=2, k=0, m; m = ++i || ++j && ++k; printf(“%d, %d, %d, %d\n”, i, j, k, m); return 0; }

29th Jul 2018, 4:17 PM
Toufiqahmed Shaikh
Toufiqahmed Shaikh - avatar
5 Answers
+ 1
Using || (logical or) you know that it is already true (=1) if the left side is true (different from zero). As i = -3 it gets pre-incremented to i = -2. Then the left side of the or-statement is -2, which is different from 0 and therefore true. This is already enough to say, that the or returns true, so the right side is not evaluated at all (to save computation time). Therefore the values of j and k stay the same. m is assigned 1 (=true), since the or expression returned true. I hope it is clear now. Otherwise feel free to ask again, if my explanation was too confusing 😅
29th Jul 2018, 4:41 PM
Matthias
Matthias - avatar
+ 1
Yes, everything different from 0 is considered true. And true is always converted to 1 j and k are not changed, because they are on the right side of the or-expression. But there is no need to compute it, since the left side is already true. Basically the first two possible outcomes of 1 || 1 = 1 1 || 0 = 1 0 || 1 = 1 0 || 0 = 0 are simplified to 1 || ? = 1 It just does not matter what's there on the right. So no need to compute anything, all on the right side is ignored, if the left side is already true. j and k are on this ignored right side and therefore they won't change.
29th Jul 2018, 5:17 PM
Matthias
Matthias - avatar
+ 1
That was so clean and clear .Thank you so much mate Appreciate it
29th Jul 2018, 5:43 PM
Toufiqahmed Shaikh
Toufiqahmed Shaikh - avatar
+ 1
Yes. Because j and k is on the right side of the or expression.
12th Aug 2018, 6:55 AM
Tanmayee Gaikwad
Tanmayee Gaikwad - avatar
0
So anything different from 1 or 0 is returned as true? And why does the values of j and k don't get changed?
29th Jul 2018, 4:52 PM
Toufiqahmed Shaikh
Toufiqahmed Shaikh - avatar