QUOTE(czilofty @ 3 Nov, 2006 - 10:41 PM)

CODE
#include <iostream>
using namespace std;
int main()
{
bool error = false;
for (int i=-3; error, i++; error = !error)
if (error)
cerr << "true ";
else
cout << "false ";
return 0;
}
I have a C++ exam coming up and I thought i knew everything we had learnt so far. However in the last lecture they gave us some practice questions, one of them was the above code. The lecturer tried to explain it to us but I didn't really get it.
The result of the above code is "false true false" and I got confused by how the multiple conditions work in the for loop (seperated by a comma). So I changed the code replacing 'error' and 'i++' with variations of 'true' and 'false'. I found that the result of the condition only depended on the last condition.
My question is this; in this code and in any code, if you have multiple conditions is the only one that counts the last one? Are the rest pointless?
Thankyou,
Isaac
Isaac
When trying this sort of experiment, sometimes a paperbased exercise is better. A for loop has three parts, being:
- initialisation
- conditional exit
- update
The initialisation and update are fairly straight forward. The conditional uses operator, and you are quite right, the expression will take the last value for the conditional exit, in this case when i==0.
As to the question are they pointless? In the example, I would have to say yes. The operator used simply prevents the state of error from being combined with i. Had this been done
for ( int i = -3 ; error && i++ ; error != error) now we have combined them logically.
The comma operator has a lot of uses, but this usage doesn't really explain it well, nor instill the way to use it.
Hope this helps.