How to evaluate the return of (if condition) when using multiple logic operators and integers | SoloLearn: Learn to code for FREE!

0

How to evaluate the return of (if condition) when using multiple logic operators and integers

While competing with a friend using (c language) here on sololearn, there wa this question: What's the output of this code? If (1 && 1 && 1 || 0) printf("a"); else printf("b"); The solution was "a".. Now I don't know what the condition returned nor why the first was chosen. Can anyone help me understand this?

5/31/2020 11:48:04 AM

Sob7yy

2 Answers

New Answer

+3

1 && 1 -> true true && 1 -> true true || 0 -> true

+1

The expression 1 && 1 && 1 || 0 will be evaluated as (((1 && 1) && 1) && 1) || 0) "&&" has higher precedence and left to right associativity. "||" too has left to right associativity. So first 1 && 1 -> 1 then 1 && 1 -> 1 then 1 && 1 -> 1 then 1 || 0 -> 1 (note in this case rhs of "||" will not be evaluated)