Aradhya
Aradhya

Reputation: 53

What's the logic behind this small c++ code?

#include <iostream>
using namespace std;

int main()
{
    int j=20;
    int i=0;
    for ( int k=0; i<10 && j>10; i++ && j--)
        cout<< "i is " <<i<< " and j is " <<j<<endl;
}

So, this is how I see it, first i is 0 and j is 20, both follows the condition, hence the output is "0 20", then i is incremented and j is decremented, thus the output should be "1 19" but the next output is "1 20", as if the j hasn't been decremented!. Why?

Upvotes: 3

Views: 152

Answers (2)

Matt
Matt

Reputation: 20766

When i==0, i++ && j-- short-circuits the first time it is called, so you end up with i==1 and j==20.

You can fix this by using the comma operator: i++, j--.

Remember, in C/C++, 0 is considered false, so 0 && x will never evaluate x since it knows the expression is false. See the above link for more detail.

Upvotes: 11

JGroven
JGroven

Reputation: 613

The expression (i++ && j++) short circuits, and J is never incremented, because (i) holds a (false) initial value. I think you want it to look more like this:

    for (int k=0; i<10 && j > 10; i++, j--)

The && operator checks the left side first for truth, and if it's false, (when i is 0, this is false) it doesn't even evaluate the right side. If the left side IS true, then and ONLY then will it check the right side of the &&.
The incremental part of the for-loop shouldn't be evaluating a boolean condition.

Upvotes: 3

Related Questions