3

I have a question concerning pre and post increments with logical operators if I have this code

void main()
{int i = - 3 , j = 2 , k = 0 , m ;
m=++i||++j&&++k;
printf("%d %d %d %d",i,j,k,m);}

knowing that the increment and the decrement operators have higher precedence than && and || So they'll be executed first Then the && is higher than
means -2||3&&1 which gives the values -2 3 1 1 for the printf

but the output I get when trying on VS2010 is -2 2 0 1

Does anyone have any explanation for that ? Regards,,

user2268349
  • 33
  • 1
  • 5
  • Please note that operator precedence is not necessarily the same thing as order of execution. What matters here apart from precedence, is _order of evaluation_, which happens to be well-defined in the specific case of the `&&` and `||` operators. – Lundin Mar 22 '17 at 14:08

1 Answers1

4

This is what you get from short circuiting. ++i is -2, and the rest doesn't have to be evaluated (and isn't according to the standard). The left side of || is true because -2 is not 0, so the whole expression is true.

chris
  • 60,560
  • 13
  • 143
  • 205
  • Doesn't the && have higher precedence than || ? I mean , for example in the multiplication and addition , multiplication has higher precedence than addition , so if we check 3+4*5 It'd be 23 and not 35 Or am I missing something ? Thanks chris for your teremendously fast reply Anyway :) – user2268349 Apr 11 '13 at 00:47
  • 5
    It's *because* it has higher precedence that this happens. The whole thing can be written as `(++i) || (++j&&++k)`. Since the left side is true, the right side is not evaluated. If `||` had higher precedence, `++i||++j` would have to be evaluated to determine whether `++k` also had to be. – chris Apr 11 '13 at 00:48
  • Thanks Chris , got you – user2268349 Apr 11 '13 at 00:49