Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I can not understand the output of this c programming. Please any one help

Tags:

c

#include <stdio.h>

int main () {
    int x, y, z;

    x = y = z = 1;
    ++x || ++y && ++z;
    printf ("x = %d\t y = %d\tz = %d\n", x, y, z);
    //op  :   x = 2    y = 1  z = 1 
    //why is 'x' only incrementd? 

    x = y = z = -1;
    ++x || ++y && ++z;
    printf ("x = %d\t y = %d\tz = %d\n", x, y, z);
    //op  :  x = 0    y = 0  z = -1
    //why are 'x' and 'y' incremented?

    x = y = z = 1;
    ++x && ++y || ++z;
    printf ("x = %d\t y = %d\tz = %d\n", x, y, z);
    //op  : x = 2    y = 2  z = 1
    //why is 'x' only incrementd?

    x = y = z = -1;
    ++x && ++y || ++z;
    printf ("x = %d\t y = %d\tz = %d\n", x, y, z);
    //op  : x = 0    y = -1 z = 0
    //why are 'x' and 'z' incremented?

    //Does this incrementation depend on the value stored in the variable?
}
like image 589
Sudarshan Roy Avatar asked Dec 03 '22 08:12

Sudarshan Roy


2 Answers

The reason is that && and || short circuit.

That is, once they know what the end result of the boolean expression will be, they stop evaluating.

So, if you do 1 || x++, then x will never be incremented, because any non-zero boolean value is a true value.

Likewise, if you do 0 && x++, x++ never will get executed either.

See also:

  • Short-circuit evaluation on Wikipedia
like image 72
Sebastian Paaske Tørholm Avatar answered Feb 06 '23 06:02

Sebastian Paaske Tørholm


|| and && short-circuit. What that means is that they perform as little work as possible to return their value, only executing the right side if the left side doesn't nail the answer.

For instance:

1 || anything();

In this case, anything() will never execute, because || can simply return as soon as it evaluates the 1; no matter what anything()'s return value, the return value of || in this expression can never be 0.

Similarly:

0 && anything_else();

Here, anything_else() will never execute, because && already knows that its value can never be anything but 0.

In your examples, the ++ preincrements don't actually affect the short-circuiting, except to hide the values that the boolean short-circuit operators are actually making their decisions on.

like image 35
regularfry Avatar answered Feb 06 '23 05:02

regularfry