Short-circuiting in C Programming Expressions………….!!!

By -

One Superb thing i learn today is  Short-circuiting in C Programming Expressions. 

Let me explain you by code

#include <stdio.h>
int main() {
   int a = 0;
   int b = 1;
   int c = 2;
   int d = 3;
   a = ++b && ++c || ++d;
   printf ("b = %d,  c = %d, d = %d, a = %d", b, c, d, a);
   return 0;

if you think output of this program will be

b = 2, c = 3, d = 4, a = 1

then you need to read this whole post..!

Output of this program is

b = 2, c = 3, d = 3, a = 1
see output at here.

Here d is not going to increment..In C programming Expressions inside conditions are evaluated from left-to-right. Here, if the first condition in the OR clause is evaluated to true, there’s no point for the second one to also be evaluated, since the whole expression is known to be true already.


++a && ++b evaluates to true.

So what ever the value of second operand in (logical OR ) || the result will be same. So here the second operand is not going to evaluated.

This behavior of   && , ||? operators in c is called Short-circuit. And this three operators are also known as Short-circuit operators.

More about this at here Short-circuit operators

Note: i know this is something like silly post but this type of concept are very helpful in debugging and in Interview question. 

hey I am an Artist who love to write code...! Well I am an EC graduate From Ganpat University and now i am working as Embedded software engineer in one private firm.. find me at here Jeegar Patel

Leave a Reply

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