0

According to the short-circuit property in C:0&&(anything) gives 0 and 1||(anything) gives 1. so according to the property-0&&5||6&&7||4&&!6,this should give us 0.

But when I tried to run this in a C compiler this gave 1 as the answer.

[Update: removed image link, just typed in the program as text.]

#include <stdio.h>

int main()
{
    int x;
    x=0&&5||6&&7||4&&!6;
    printf("%d",x);
    return 0;
}

Can anybody tell me what am I missing or doing wrong?

ndim
  • 35,870
  • 12
  • 47
  • 57

1 Answers1

1

Let me try explain what is happening, then you can follow along and find by yourself what you were missing.

Let's start with your original expression

0&&5||6&&7||4&&!6

This expression is written as a short form without any parentheses.

This is similar to standard mathematical expressions where 2*7+3*8 is understood to mean that the * has precedence over +, so this is actually a short form for (2*7)+(3*8), and 2*7+3*8+4*3 is short form for ((2*7)+(3*8))+(4*3).

In the same way, the above C expression implicit operator precedence can be made explicit by rewriting with parentheses:

( (0&&5) || (6&&7) ) || (4&&!6)

The above step appears to be what you are missing, and therefore you are misinterpreting the meaning of the written expression.

We can then consider the three small parentheses separately:

  • (0 && whatever) is 0 (short circuit applies)
  • (6 && 7) is 1 (both 6 and 7 are non-zero i.e. true, so result is true)
  • (4 && !6) is nonzero && zero is zero is 0 (which, as it turns out later, we do not actually need to evaluate)

So... the whole expression

( (0&&5) || (6&&7) ) || (4&&!6)

turns out to be

( 0 || 1 ) || does_not_matter

or

1          || does_not_matter     (short circuit applies)

which is 1.

ndim
  • 35,870
  • 12
  • 47
  • 57
  • But why should go through such a process like taking precedence or evaluating the terms,according to short circuit property for 0&&(anything) shouldnt we just directly ignore the 'anything' part and directly put 0 as answer. plz correct me if im understanding anything wrong. – Subham Bhuyan Dec 09 '22 at 20:25
  • The original expression assigned to `x` is not `0 && (anything)`. It is `( (0&&doesnotmatter) || (nonzero && nonzero) ) || turnsoutitdoesnotmatter`. Similar to normal arithmetic terms where you do not need to write the parentheses in `(3*7) + (2*8)`, so the expression `3*7+2*8` is the same. – ndim Dec 09 '22 at 20:29