1
printf ("%d \n", 2 > !3 && 4 - 1 != 5 || 6 ) ;

Can someone explain to me how this is evaluated ? What I am most confused about is the ! symbol in front of the 3... how to evaluate 2 > !3 ?

Ajinkya
  • 22,324
  • 33
  • 110
  • 161
wadafarfar
  • 41
  • 2

4 Answers4

3

! is the logical not. Meaning it returns 1 for 0 or 0 for any other value.

!0 == 1

!1 == 0

!897489 == 0 

So in your example 2 > !3 will be evaluted 2 > 0 which is 1

For your whole expression you will have

2 > !3 && 4 - 1 != 5 || 6 
2 > 0  && 3 != 5 || 6
1 && 1 || 6                    && is higher precedence || but some compiler will warn (gcc)
1 || 6                         the 6 will not be evaluated (touched) because of short-circuit evaluation
1
Patrick Schlüter
  • 11,394
  • 1
  • 43
  • 48
2

Here is a table of operator precedence. From this we can deduce that in your expression

  • ! has the highest precedence
  • - comes next
  • > comes next
  • != comes next
  • && comes next
  • || comes next

! means logical not !0 == 1, !anythingElse == 0.

The expression is evaluated as

((2 > (!3)) && ((4 - 1) != 5)) || 6

Generally, the order of evaluation of the operands is unspecified, so in the case of

2 > !3 

the compiler is free to evaluate !3 before evaluating2

However, for && and ||, the left side is always evaluated first so that short circuiting can be used (with && if the left side is false (0), the right side is not evaluated, with || if the left side is true (anything but 0), the right side is not evaluated). In the above, the 6 would never be evaluated because the left side of || is true. With

6 || ((2 > (!3)) && ((4 - 1) != 5))

6 is true so the right side will never be evaluated.

JeremyP
  • 84,577
  • 15
  • 123
  • 161
0

Its best to use parentheses to have your own order. Otherwise, operator precedence is explained in the C Operator Precedence Table.

From the above link:

  1. !3

  2. 2 > !3

Wladimir Palant
  • 56,865
  • 12
  • 98
  • 126
Ozair Kafray
  • 13,351
  • 8
  • 59
  • 84
0

the ! sign convert the value in 0 in binary so 2>!3 means 2>0 and this will be always true and 4-1 equals to 3 not equals to 5||6. 5||6 gives you 1 always so the whole command print 1

Ankur
  • 3,584
  • 1
  • 24
  • 32