Reputation: 389
int j=4;
(!j!=1)?printf("Welcome"):printf("Bye");
In the above code segment, according to me, first j!=1
will result in true and !true
is false which must result in printing Bye
but I get Welcome
as the output.
Can anyone explain this one?
Upvotes: 0
Views: 83
Reputation: 34608
!
executed first because unary operator !
has a higher precedence than !=
.
!4
become 0
then 0 != 1
become true
.
So, output is Welcome
.
Upvotes: 2
Reputation: 1108
The unary operator '!' has a higher precedence than '!='.
Read - https://www.tutorialspoint.com/cprogramming/c_operators_precedence.htm.
Upvotes: 2
Reputation: 10350
The Logical NOT operator !
has a higher precedence than the Not Equal To operator !=
So your condition is equivalent to ((!j) != 1)
See https://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedence
Upvotes: 2
Reputation: 1396
This is because !
(NOT) has higher operator precedence than !=
so...
j = 4; // 4
!j // 0
In your condition, 0 != 1
will be true so "Welcome" is printed.
For your desired outcome, your condition would have to be !(j!=1)
.
Upvotes: 2