Home > Blockchain >  How this logical expression is evaluating
How this logical expression is evaluating

Time:11-23

#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:

  1. Pre- and post- increment and decrement. a increments a before the value is used in an expression, while a increments a after the value is used in the expression.
  2. Operator precedence. Specifically, && has higher precedence than ||, which means that the assignment of d should be should be read as d = (a ) || ( b && c );
  3. 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...
  4. 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.
  5. Implicit casting to boolean. In C, if an int is cast to a bool, a nonzero value becomes true, while 0 becomes false. When converting the other way, false becomes 0 and true becomes 1.

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 d needs to be assigned. To determine the value assigned to d, the left hand term of (a ) || ( b && c ) is evaluated, which is a . The value USED in the expression is 10, however the value of a after this expression is -9 due to the post-increment.
  • When cast to a boolean, the value 10 becomes true. This means that the value of the || expression must be true. Because of short-circuit evaluation, this means that b && c is not evaluated at all, so the increments do not happen.
  • The value to be assigned to d is true, but cast to an int. The result is 1, so we have d = 1.
  • Finally, the values are: a = -9, b = 3, c = 0, d = 1.

So the program prints out -9 3 0 1.

  •  Tags:  
  • c
  • Related