Strange problem...

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • howa

    #1

    Strange problem...

    int n , i = 10, j =20, y=100, x = 3;

    n = ( i < j ) || (y +=i) ;

    cout<<y;

    // why y = 100, but not 110, as y +=i , y = y + i

  • Larry Smith

    #2
    Re: Strange problem...

    howa wrote:
    int n , i = 10, j =20, y=100, x = 3;
    >
    n = ( i < j ) || (y +=i) ;
    The above evaluates left-to-right.
    Since it is a logical 'or', if the first expression,
    (i < j), evaluates to 'true', then the second expression,
    (y += i), is NOT evaluated.

    >
    cout<<y;
    >
    // why y = 100, but not 110, as y +=i , y = y + i
    >

    Comment

    • Greg Comeau

      #3
      Re: Strange problem...

      In article <1161916770.479 434.313150@e3g2 000cwe.googlegr oups.com>,
      howa <howachen@gmail .comwrote:
      > int n , i = 10, j =20, y=100, x = 3;
      >
      > n = ( i < j ) || (y +=i) ;
      >
      > cout<<y;
      >
      >// why y = 100, but not 110, as y +=i , y = y + i
      This is so-called short-circuting of expressions.
      When expressions are seperated by || it will take each in turn,
      if the value of the current is false, it continues to the next;
      if the value of the current is true, the full expression is deemed
      successful and no need to continue to be more successful
      therefore subsequent parts are not evaluated to be more successful.
      In your specific example i is < j, therefore, the y+=i expression
      is not evaluated.
      --
      Greg Comeau / 20 years of Comeauity! Intel Mac Port now in beta!
      Comeau C/C++ ONLINE == http://www.comeaucomputing.com/tryitout
      World Class Compilers: Breathtaking C++, Amazing C99, Fabulous C90.
      Comeau C/C++ with Dinkumware's Libraries... Have you tried it?

      Comment

      Working...