#include<stdio.h>
int main()
{
int a=-10,b=3,c=0,d;
d= a || b &&c ;
printf("%d %d %d %d ",a,b,c,d);
}
How above expression is evaluates. I have read preceedence but still i am getting confused. Kindly give me the right solution of this in step by step.
CodePudding user response:
In case of || and && operators the order of evaluation is indeed defined as left-to-right.So, operator precedence rules tell you that the grouping should be
(a ) || (( b) && (c ))
Now, order-of-evaluation rules tell you that first we evaluate a , then (if necessary) we evaluate b, then (if necessary) we evaluate c , then we evaluate && and finally we evaluate ||.
CodePudding user response:
I have a feeling this is a homework question, so I'll try to give extra explanation. There are actually a lot of concepts going on here!
Here are the main concepts:
- Pre- and post- increment and decrement.
aincrementsabefore the value is used in an expression, whileaincrementsaafter the value is used in the expression. - Operator precedence. Specifically,
&&has higher precedence than||, which means that the assignment ofdshould be should be read asd = (a ) || ( b && c ); - Expression evaluation order. The link shows a whole list of evaluation rules for C. In particular, item 2 says (paraphrasing) that for operators
||and&&, the entire left side is always fully evaluated before any evaluation of the right-hand side begins. This is important because of... - Short-circuit boolean evaluation, which says that, for operators
&&and||, if the value of the left-hand term is enough to determine the result of the expression, then the right-hand term is not evaluated at all. - Implicit casting to boolean. In C, if an
intis cast to abool, a nonzero value becomestrue, while0becomesfalse. When converting the other way,falsebecomes0andtruebecomes1.
Putting this all together, here is what happens:
- After the first line, a is -10, b is 3, c is 0 and d is unset.
- Next, the variable
dneeds to be assigned. To determine the value assigned tod, the left hand term of(a ) || ( b && c )is evaluated, which isa. The value USED in the expression is 10, however the value ofaafter this expression is -9 due to the post-increment. - When cast to a boolean, the value
10becomestrue. This means that the value of the||expression must betrue. Because of short-circuit evaluation, this means thatb && cis not evaluated at all, so the increments do not happen. - The value to be assigned to
distrue, but cast to anint. The result is 1, so we haved = 1. - Finally, the values are: a = -9, b = 3, c = 0, d = 1.
So the program prints out -9 3 0 1.
