edited by
1,426 views

1 Answer

3 votes
3 votes

Anyone who have read about undefined value in C language might think that the answer here is Undefined. But, in the definition of undefined value, its clearly mentioned about sequence points and logical operators || and && are pat of sequence points. That is, all the side effects of evaluation of expression on the left side of these operators must be completed before evaluating the right side. This is done so that short circuiting rule (explained below) would work in C.

Short circuiting rule is used to short circuit the evaluation of an expression as soon as the result of the whole expression is known. i.e.; Once the end result of an expression is determined at some point during the evaluation of that expression, the evaluation of the remaining part of that expression is skipped. This happens in the case of logical operators && and ||.

In the code above, consider the statement

 b = ++a || ++a;

Here, we know the end value of || operator, even before we evaluate the right hand side of ||, as ++a returns a positive number. Hence, the compiler will skip the execution of the remaining part of the expression. Thus a is incremented only once (to 2) and b is assigned the result of || operator which is 1.

Similarly for && operator, the second part of the expression wont be evaluated if the first half evaluates to 0.

Short circuiting rule is provided not only to avoid execution of dead codes but also as a means of error handling. For example, in the left hand side of && we can check the index of an array to be within the array bounds and then in the right hand side, access the array element.

Answer:

Related questions

1 votes
1 votes
2 answers
1
Ashwani Kumar 2 asked Oct 16, 2017
764 views
int main() { int i=-1, j=-1,k=0,l=2,m; m= i++ && j++ && k++ || l++ ; printf("%d %d %d %d %d", i,j,k,l,m); return 0; }
7 votes
7 votes
2 answers
2
Arjun asked Oct 18, 2016
867 views
What will be the outout of the following code?#include <stdio.h int main() { int a = 1, b = 2; int c = a++ || b++; printf("%d %d %d", a, b, c); }1 2 12 3 12 2 12 2 0
2 votes
2 votes
1 answer
3