counting even numbers

Write here if you have problems with your C++ source code

Moderator: Board moderators

Post Reply
Artikali
Learning poster
Posts: 68
Joined: Wed Sep 21, 2005 5:27 pm

counting even numbers

Post by Artikali » Sun Mar 26, 2006 4:44 am

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

Code: Select all

while((i-=2) && cout<<i<<endl);

chunyi81
A great helper
Posts: 293
Joined: Sat Jun 21, 2003 4:19 am
Location: Singapore

Post by chunyi81 » Sun Mar 26, 2006 5:29 am

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.

Artikali
Learning poster
Posts: 68
Joined: Wed Sep 21, 2005 5:27 pm

Post by Artikali » Sun Mar 26, 2006 6:38 am

thanks.
what is the return value of

Code: Select all

cout<<i<<endl;

User avatar
Krzysztof Duleba
Guru
Posts: 584
Joined: Thu Jun 19, 2003 3:48 am
Location: Sanok, Poland
Contact:

Post by Krzysztof Duleba » Sun Mar 26, 2006 10:56 am

It's cout, which has boolean value of true if everything is ok with the stream.

User avatar
Krzysztof Duleba
Guru
Posts: 584
Joined: Thu Jun 19, 2003 3:48 am
Location: Sanok, Poland
Contact:

Post by Krzysztof Duleba » Sun Mar 26, 2006 11:03 am

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.

chunyi81
A great helper
Posts: 293
Joined: Sat Jun 21, 2003 4:19 am
Location: Singapore

Post by chunyi81 » Wed Mar 29, 2006 9:10 am

Thanks Krzysztof for correcting my mistakes. :oops:

Post Reply

Return to “C++”