Page 1 of 1
counting even numbers
Posted: Sun Mar 26, 2006 4:44 am
by Artikali
I couldn't understand this code please help me
Code: Select all
#include <iostream>
using namespace std;
int main(){
int i=10;
while(i-=2 && cout<<i<<endl);
return 0;
}
output is counting from 10 to 1, with odd numbers
why this code counting with odd numbers
it will work if i changed
Posted: Sun Mar 26, 2006 5:29 am
by chunyi81
Looks like an operator precedence problem. Expressions in C++ are evaluated from right to left and logical operators always have a higher precedence in evaluating an expression, which means that in the first code,
2 && cout << i << endl is evaluated first -> this always give 1.
Now the while loop condition simplifies to while (i -= 1). Notice that it decrements by 1 every time.
For the second code you explicitly put i -= 2 in brackets, which means that i decrements by 2 each time you output i. Now the expression i -= 2 will be evaluated first followed by the logical expression (i -= 2) && (cout << i << endl) as the parantheses give the operator -= a higher precedence than the logical && operator.
Posted: Sun Mar 26, 2006 6:38 am
by Artikali
thanks.
what is the return value of
Posted: Sun Mar 26, 2006 10:56 am
by Krzysztof Duleba
It's cout, which has boolean value of true if everything is ok with the stream.
Posted: Sun Mar 26, 2006 11:03 am
by Krzysztof Duleba
Two notes:
chunyi81 wrote:Expressions in C++ are evaluated from right to left
That's not true, only assignments are right-associative.
chunyi81 wrote:2 && cout << i << endl is evaluated first -> this always give 1.
Only if everything is fine with cout. If you close stdout or an error occurs, this expression will evaluate to false.
Posted: Wed Mar 29, 2006 9:10 am
by chunyi81
Thanks Krzysztof for correcting my mistakes.
