开发者

Trouble with this C++ snippet

开发者 https://www.devze.com 2023-04-05 12:31 出处:网络
I don\'t understand what this snippet is do, if anyone could explain it would help out a great deal. bool result;

I don't understand what this snippet is do, if anyone could explain it would help out a great deal.

    bool result;
    for (std::set<_Tp>::const_iterator o = objs.begin(); o != objs.end(); o++)
    {
      //confusion here, what does this do
      result |= accept(c, *o, bid); //accept returns a bool
    }

    return result;
  }

I know that the |= compound operator does a bitwise OR but what does that mean for the value of result? If accept returns true then the value of result will stay true, right?

I guess I don't really understand why the |= is there in开发者_运维知识库stead of =

Any help would be great

Thanks


|= is a bitwise or, not a logical or. You have removed the logic out of the snippet, but basically what it does is return true as long as any object within the set is 'accepted', whatever the definition of accept is.


x |= y is equivalent to x = x | y. So what

result |= accept(...);

does is set result to true if accept returns true -- and leave it alone if accept returns false.

|, as opposed to ||, is a bitwise operation, but for bool values it gives the same result. (And there is no ||= operator, probably because || has short-circuit semantics.)

I hope that wasn't all the code. In the code you showed us, result is uninitialized.


It checks if any one of return values from the function accept is true. If you replaced the |= with the = then if the last call to accept returned false then the final result would also be false. Any previous value would be overwritten. Using |= instead allows you to keep the previous results.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号