Using && in a for loop help

Hello! I'm pretty much a beginner learning C++, I was doing an exercise to reverse a string when I came across a problem in the for loop. The code is:

1
2
3
4
5
6
7
8
9
10
11
12
int main()
{
    int i = 0, j = 6;
    //while(i<3)
    for(i, j; i < 3; i++ && j--)
    {
        cout << "I = " << i << endl;
        cout << "J = " << j << endl;
        cout << "*****************" << endl;
        //++i && j--;
    }
}


The output I get is

1
2
3
4
5
6
7
8
9
10
I = 0
J = 6
*****************
I = 1
J = 6
*****************
I = 2
J = 5
*****************


Why is J not 5 the second time the loop is executed? I found that if I write

 
for(i, j; i < 3; ++i && j--)


I get the expected output:
1
2
3
4
5
6
7
8
9
10
I = 0
J = 6
*****************
I = 1
J = 5
*****************
I = 2
J = 4
*****************


Am I missing something incredibly stupid here?
&& isn't doing what you think it is, here. You're hitting something called "short circuiting" which I'm too lazy to explain right now.

If you want to combine two actions, you'd use the comma operator instead of &&:

1
2
3
4
for(; i < 3; ++i, --j)
{
    //...
}


Notice:
- There's no need for i, j as that serves no purpose
- use comma for increment/decrement rather than &&



&& should only really be used in conditional statements where there are multiple conditions to check:

 
if( something && something_else )
Disch, Thank you very much! Knew it had to be something dumb I was doing! What confuses me a bit is why it is evaluated after the first loop. I did read up on short circuiting so thanks for pointing that out.
Last edited on
Topic archived. No new replies allowed.