# Operators : Short circuit behavior of logical operators

0 like 0 dislike
330 views

Short circuiting is a functionality that skips evaluating parts of a (if/while/...) condition when able.

0 like 0 dislike
by Goeduhub's Expert (9.3k points)

Short circuiting is a functionality that skips evaluating parts of a (if/while/...) condition when able. In case of a logical operation on two operands, the ﬁrst operand is evaluated (to true or false) and if there is a verdict (i.e ﬁrst operand is false when using &&, ﬁrst operand is true when using ||) the second operand is not evaluated.

Example:

#include <stdio.h>

int main(void) {  int a = 20;  int b = -5;

/* here 'b == -5' is not evaluated,     since a 'a != 20' is false. */

if (a != 20 && b == -5)

{

printf("I won't be printed!\n");

}

return 0;

}

Check it out yourself:

#include <stdio.h>

int print(int i)

{

printf("print function %d\n", i);

return i;

}

int main(void)

{

int a = 20;

/* here 'print(a)' is not called,     since a 'a != 20' is false. */

if (a != 20 && print(a))

{

printf("I won't be printed!\n");

}

/* here 'print(a)' is called,     since a 'a == 20' is true. */

if (a == 20 && print(a))

{

printf("I will be printed!\n");

}

return 0;

}

Output:

\$ ./a.out

print function 20

I will be printed!

Short circuiting is important, when you want to avoid evaluating terms that are (computationally) costly. Moreover, it can heavily aﬀect the ﬂow of your program.

Learn & Improve In-Demand Data Skills Online in this Summer With  These High Quality Courses[Recommended by GOEDUHUB]:-

Best Data Science Online Courses[Lists] on:-

Claim your 10 Days FREE Trial for Pluralsight.