Question

Is there something like in-place AND and OR operators for bools in c++, along this line?

bool someOk=false;
for(int i=0; i<10; i++){
  someOk||=funcReturningBoolOnSuccess(i);
}

(I know I can write someOk=someOk||funcReturningBoolOnSuccess(i), but it is not as pretty).

Was it helpful?

Solution

The answer will be short: no, the C++ syntax does not allow such structure.

You have to use:

something = something || something_else;

However.... if your function returns bool on success (as in, true on success)... Why don't you just use the following?

someOk = funcReturningBoolOnSuccess(i);

Will it not return false on failure anyway? Seems illogical.

Why don't you just do:

bool someOk=false;
for(int i=0; i<10; i++){
  if (funcReturningBoolOnSuccess(i)) {
      someOk = true;
      break;
  }
}

A lot more efficient :)

OTHER TIPS

As long as the return is bool, you can use |= for this purpose (unless you strictly want to avoid calling funcReturningBoolOnSuccess(i); after the first success - in which case you have to use some if and break or change the condition of the for loop).

If the result is not bool value, then you probably need to convert it to that, since |= is indeed a bitwise operation. Any basic type in C or C++ can be converted to a bool by the simple trick of !! ("bang-bang" or "not-not") - it makes a true of anything non-zero and false of a zero result, which is what we want.

I know it's not in-place, but it's easier to use.

void OR(bool& x,bool y)
{
   x = x || y;
}

/* later on */

bool someOk = false;

// someOk = false
// funcRetBoolOnSuc(8) = false
OR(someOk,funcRetBoolOnSuc(8));
// someOk = false

// someOk = false
// funcRetBoolOnSuc(8) = true
OR(someOk,funcRetBoolOnSuc(9));
// someOk = true

Or, because bool accepts only 0,1 as values you could do this:

someOk |= funcRetBoolOnSuc(x);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top