Ravi S
Ravi S

Reputation: 15

Can someone explain me why I am getting two different answers for the below codes?

#include <stdio.h>
int main()
{
    int x = 2, y = 0;
    int m = (y |= 10);
    int z = y && m;
    printf("%d\n", z);
    return 0;
}

Above program gives me output as 1. Below code is giving me output 0 but what is the reason for different outputs here?

#include <stdio.h>
int main()
{
    int x = 2, y = 0;
    int z = y && (y |= 10);
    printf("%d\n", z);
    return 0;
}

Upvotes: 0

Views: 51

Answers (1)

Jean-Fran&#231;ois Fabre
Jean-Fran&#231;ois Fabre

Reputation: 140297

In

int z = (y |= 10);

y is masked with 10 so set to 10, so y && m is a boolean worth 1 because both y and m are non-zero, assigned to z

Now, in

int z = y && (y |= 10);

y == 0 so && short-circuits, not evaluating the right hand part and not changing the value of y. Therefore, z is set to 0.

Had you used:

int z = y & (y |= 10);

this would have depended on how/in which order the compiler evaluates the operands (implementation defined behaviour to get 0 or 10)

note that && short-circuiting doesn't evaluate the second parameter if the first is zero for a very good reason:

if ((pointer != NULL) && pointer->value == 12) { do_something(); }

this condition checks if the value is 12 but only if the pointer is non-NULL. If the second expression was evaluated first, this could crash.

Upvotes: 1

Related Questions