0

There are some cases which i'll have to loop through an array/vector looking for an element that satisfies a condition that involves the element's value.In the past i'd go for a simple for loop together with an if statement, but lately i saw a piece of code that seems more simple.To be precise:

I used to do it like this:

for( int i = 0; i < vector.size(); i++ )
    if( condition[i] )
       do_stuff;

And now im curious about this one:

int i = 0;
while( i < vector.size() || condition[i] )
    i++;

I like that definition,it's shorter and in fact i believe it's easier to read,but what bothers me is the case where the vector is empty.

I'm not sure about the way || processes the boolean values, does it check the first condition and if it's false goes for the second one? Or does it check both nevertheless? If that's the case,there should be an error since Im checking for a condition on an element that doesn't exist.

After trying the code on an empty vector it compiled and ran just fine,just to ensure i tried this one as well:

bool a , b = false;
if( b || a )
   dostuff;

And it worked just fine as well.

But it still doesn't seem completely right to me checking conditions on nonexisting values and im not sure if i should use it.Is it okay or should i go for something else?

Any help would be great.

Edit 0: Still it should throw an error since the vector is empty. 0 < 0 returns false , so the second condition will still be checked.

  • 3
    `i < vector.size() || condition[i]` is wrong even with short-circuit evaluation because if the first part is `false`, the second part will be checked _and_ `i` will be out of bounds. – chris May 07 '20 at 02:59

1 Answers1

2

Yes, operator|| performs short-circuit evaluation.

Builtin operators && and || perform short-circuit evaluation (do not evaluate the second operand if the result is known after evaluating the first), but overloaded operators behave like regular function calls and always evaluate both operands

That means for while( i < vector.size() || condition[i] ), if i < vector.size() is true then condition[i] won't be evaluated; if it's false then condition[i] will be evaluated further; now you might see there's an error here.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405