Short Circuit Feature For Logical Operators

code:

#include<stdio.h>
int main()
{
    int a=-1,b=10,c;
    c=++a && ++b;
    printf("a=%d, b=%d, c=%d\n",a,b,c);

    return 0;
}

Expected Output:

a=0, b=11, c=0

Coming Output:

a=0, b=10, c=0

Why this happen?
It happens because left to right associativity of this and when left operand is o it means false so in and it does not go to the right.

Let’s see another example:

#include<stdio.h>
int main()
{
    int a=5,b=10,c;
    c=++a && ++b;
    printf("a=%d, b=%d, c=%d\n",a,b,c);
    return 0;
}

Output:

a=6, b=11, c=1

This is happening because left to right associativity and left one is true so it is also iterating to the right one.

For OR operation:

#include<stdio.h>
int main()
{
    int a=0,b=10,c;
    c=++a || ++b; //&&
    printf("a=%d, b=%d, c=%d\n",a,b,c);
    return 0;
}

Output:
a=1, b=10, c=1
because in OR if left value is true then another in right will not be increment
Another example:

#include<stdio.h>
int main()
{
    int a=-1,b=10,c;
    c=++a || ++b; //&&
    printf("a=%d, b=%d, c=%d\n",a,b,c);
    return 0;
}

Output:
a=0 b=11 c=1

here left value a is 0 that means it is false so another right value is incrementing and so b=11. and c is 1 as in or if one value is ture it is true.

It would be a great help, if you support by sharing :)
Author: zakilive

Leave a Reply

Your email address will not be published. Required fields are marked *