1

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.

paddy
  • 60,864
  • 6
  • 61
  • 103
GG33
  • 31
  • 3
  • 1
    `||` and `&&` short circuit... i.e in `true || foo()` and `false && foo()` , `foo` is not called. – Jarod42 Dec 22 '22 at 00:31
  • Did you observe anything which makes you think that you are mistaken? Can you provide an [mre] of that? – Yunnosch Dec 22 '22 at 01:30

1 Answers1

1

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.

Daksh
  • 449
  • 5