What is the use for this Condition in the for loop for(int i = 0; i < m and n; i++)?

85 Views Asked by At

I encountered a question in competitive programming and the solution for that include a for loop with a syntax like

for(int i = 0; i < m and n; i++){
    //Do Something
}

When I changed the condition from i < m and n to i < m and submitted the solution it was giving TLE whereas in the i < m and n condition the Solution was Accepted.

What is the use of i < m and n condition if the loop runs only m times? And I don't feel like m would exceed n (if the answer is it looks for both the variables in an and comparison). What is the impact in time Complexities?

1

There are 1 best solutions below

0
Vlad from Moscow On BEST ANSWER

According to the C++ Standard (for example C++ 14 Standard4,section 12 Boolean conversions)

1 A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true. For direct-initialization (8.5), a prvalue of type std::nullptr_t can be converted to a prvalue of type bool; the resulting value is false.)

So this expression

i < m and n

is equivalent to

i < m and n != 0

that is the same as

i < m && n != 0

or if to make it more clear

( i < m ) && ( n != 0 )

and in the expressipn is an alternative representation of the logical AND operator &&.

It seems that within the body of the loop (or before the loop) the variable n can be changed and as a result can be equal to 0. In this case the loop will be interrupted even if i is less than m.