C Relational Operator Output
Asked Answered
V

3

6
#include <stdio.h>
void main()
{
    int x = 1, y = 0, z = 5;
    int a = x && y || z++;
    printf("%d", z);
}

This yields output as 6 whereas

#include <stdio.h>
void main()
{
    int x = 1, y = 0, z = 5;
    int a = x && y && z++;
    printf("%d", z);
}

this would yield answer as 5. WHY ?? Someone please explain.

Venavenable answered 27/12, 2015 at 19:11 Comment(1)
What did you expect and why?Multinuclear
S
6

This is due to the Short Circuit mechanism.

What this means is that when the result of a logical operator is already determined, the rest of the expression isn't evaluated at all, including potential side effects.

The first code fragment behaves like:

int a = (1 && 0) /* result pending... */ || z++;

And the second:

int a = (1 && 0) /* result determined */;

This happens because the value of a logical AND is known to be false if the left side expression is false.

Shabuoth answered 27/12, 2015 at 19:17 Comment(0)
M
6

As you can probably tell, the difference between two fragments of code is that the first one evaluates z++, while the other one doesn't.

The reason the second code does not evaluate z++ is that the expression ahead of it evaluates to false, so && chain "short-circuits" the evaluation of the last term.

Operator ||, on the other hand, would short-circuit only when the left side is true.

Mancuso answered 27/12, 2015 at 19:20 Comment(0)
C
2

For starters function main without parameters shall be declared like

int main( void )

In the first program the initialization expression can be represented like

int a = ( x && y ) || ( z++ );

According to the C Standard (6.5.14 Logical OR operator)

  1. ...If the first operand compares unequal to 0, the second operand is not evaluated.

The first oerand ( x && y ) of the expression is equal to 0 because y is initialized by 0

int x = 1, y = 0, z = 5;

So the second operand ( z++ ) is evaluated.

As result z will be equal to 6.

In the second program the initialization expression can be represented the same way as in the first program

int a = ( x && y ) && ( z++ );

According to the C Standard (6.5.13 Logical AND operator)

  1. ...If the first operand compares equal to 0, the second operand is not evaluated.

As before the first operand ( x && y ) of the expression is equal tp 0 and according to the quote the second operand ( z++ ) is not evaluated.

As result z will be equal to 5 as before.

Coleoptile answered 27/12, 2015 at 19:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.