简体   繁体   中英

Evaluating an expression containing logical and increment operators in c

I'm trying really hard to understand how this expression is evaluated in c even though I know the precedence and associativity of operators in c language

   int i=-4,j=2,k=0,m;
   m = ++i || ++j && ++k;

As far as I know the pre increment operators are evaluated first from left to right the the logical and is then the logical so the I value will be -3 the j value will be 3 the k value will be 1 and for m value its 1 but it seems that I'm mistaken.

I'm studying this for an upcoming exam and ill appreciate any help.

The part that you're possibly missing while trying to understand the logic behind the final values obtained is what is known as short circuiting in C.

A summary of what it is -

if the first operand of the ||operator compares to 1, then the second operand is not evaluated. Likewise, if the first operand of the && operator compares to 0, then the second operand is not evaluated.

Going by the above rules, the unary operation on i ( ++i ) returns with 1 and hence the following operands of the ||statement are essentially ignored. Therefore, the value of all other variables remains unaffected and m receives the value 1 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM