+ 3
What is the output of this code(c++)? And how?
int x = 5; cout << (x>5||(x==5 & & x==6||x<5)); /*I m having problems solving the question of logical operators in challenges... How can i improve my knowledge of logical operators? Plz help */
2 odpowiedzi
+ 3
This is called "operator precedence"
And basically, what it does is define which operator should be evaluated first.
Paréntesis is evaluate first, then evaluate multiplication, division and reminder
Then follows addition and subtraction
Then follows relational operators such as < <= > >= == !=
Then follows logical &&
And then ||
Let's break down your code
1- resolve internal paréntesis
2- x==5 (true)
3- && (need to evaluate anything to the right)
4- x==6 (false)
5- joining #2 && #4 (false)
6- ||
7- x<5
8- joining #5 || 7 (false)
9- now inner paréntesis was resolved continue
10- x>5 (false)
11- joining #10 || inner paréntesis result (false)
Btw, the associativity for Operator Precedence is not always the same. e,g increment operators are from right-to-left but, in your case is from Left-to-right.
+ 19
0
First the bracket will be solved...
x==6 || x<5..... will give 0 as it is false as both condition are false..
x==5 && 0 will give overall result of brackets as 0..
x>5 || 0 will give 0 as 5 is not greater than 5..
Thus output 0