Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Relational Operator Output

#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.

like image 557
Srijan Kumar Avatar asked Dec 27 '15 19:12

Srijan Kumar


People also ask

What is the output of relational operator?

The output of the relational operator is (true/false) boolean value, and in Java, true or false is a non-numeric value that is not related to zero or one.

What is the relational operator in C?

C Relational Operators A relational operator checks the relationship between two operands. If the relation is true, it returns 1; if the relation is false, it returns value 0. Relational operators are used in decision making and loops.

What is -= in C?

-= Subtract AND assignment operator. It subtracts the right operand from the left operand and assigns the result to the left operand. C -= A is equivalent to C = C - A.


1 Answers

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.

like image 148
Amit Avatar answered Sep 29 '22 10:09

Amit