logical expression

I have 4 pair of logical expressions, each pair should be logically equivalent. Can anyone explain why the third pair does not give the same resoult please?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 #include <iostream>
using namespace std;

int main(){
int x=7;
int y=6;
int a=4;
int b=3;

cout <<         !((x<=6)&&(y%2==1));
cout << "\n" << !(x<=6)||!(y%2==1);
cout << endl;
cout << "\n" << !((a<4)||(b>=6));
cout << "\n" << !(a<4)&&!(b>=6);
cout << endl;
cout << "\n" << !(x<3)&&!(y>=2);
cout << "\n" << !((x<3)||(y>=2));
cout << endl;
cout << "\n" << !(a==b)||!(b!=2);
cout << "\n" << !((a==b)&&(b!=2));
}
Change those lines to
1
2
3
4
int c = !(x<3)&&!(y>=2);
int d = !((x<3)||(y>=2));
cout << "\n" << c;
cout << "\n" << d;

and it will give what you expect.


See:
https://en.cppreference.com/w/cpp/language/operator_precedence
and, in particular,
When parsing an expression, an operator which is listed on some row of the
table above with a precedence will be bound tighter (as if by parentheses) to its arguments than
 any operator that is listed on a row further below it with a lower
 precedence. For example, the expressions std::cout << a & b and *p++ are parsed as
 (std::cout << a) & b and *(p++), and not as std::cout << (a & b) or (*p)++. 
Last edited on
Topic archived. No new replies allowed.