Home > database >  What actually happens when this type of condition in the for loop is checked?
What actually happens when this type of condition in the for loop is checked?

Time:11-18

I can't understand the difference between the condition checked in a for loop and an if condition. Do both behave in a different way?

When I write:

int num = 10;
for(int i = 0; i < 15 && num; i  ){
    cout << i << " ";
}

It only checks whether i < 15 and it doesn't check for i < num and prints all the way from 0 to 14.

But at the same time, if I write a if condition like:

if(x < 15 && num)

It checks for both x < 15 and x < num.

CodePudding user response:

The condition of a loop (whether a for loop, a while loop, or a do..while loop), and the condition of an if, are both boolean contexts and thus work in exactly the same way.

Both of your assertions are wrong, in that the compiler never checks for either i < num or x < num in your example, that is not how && works.

In for(int i = 0; i < 15 && num; i ), the condition is parsed as (i < 15) && (num != 0), which in your example is effectively (i < 15) && true, or simply (i < 15). If you want to check for (i < num) then you need to code it that way:

for(int i = 0; i < 15 && i < num; i  )

Alternatively:

for(int i = 0; i < min(15,num); i  )

In if(x < 15 && num), the condition is parsed as (x < 15) && (num != 0), which in your example is effectively (x < 15) && true, or simply (x < 15). If you want to check for (x < num) then you need to code it that way:

if(x < 15 && x < num)

Alternatively:

if(x < min(15,num))

CodePudding user response:

&& num doesn't do what you think it does. If you expect it to mean "now take the preceding operation, replace (whatever) with num in it and do it again", then no, it is very far from that.

it checks for both x<15 and x<num

You are mistaken, it doesn't do that. Test for num == 12, x == 13 to convince yourself. If you want to check for both x < 15 and x < num, just say so:

if (x < 15 and x < num)

Or you can use &&

if (x < 15 && x < num)

(&& and and are two spellings for the exact same thing).

  • Related