Strange problem...

H

howa

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
 
L

Larry Smith

howa said:
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.
 
G

Greg Comeau

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,677
Members
48,796
Latest member
Greg L.

Latest Threads

Top