Why is callback called once only?
bool callback() { static bool res = false; res = !res; return res; } int main(int argc, char* argv[]) { vector<int> x(10); bool result=false; for_each(x.begin(),x.end(),var(result)=var(result)||bind(callback)); return 0; }
The
||expression short circuits after the first timebindreturnstrue.The first time you evaluate
bindis called, because that’s the only way to determine the value offalse || bind(...). Becausebind(...)returnstrue,resultis set totrue.Every other time you say
… the
bind(...)expression isn’t evaluated, because it doesn’t matter what it returns; the expressiontrue || anythingis alwaystrue, and the||expression short circuits.One way to ensure that
bindis always called would be to move it to the left side of the||, or change the||to an&&, depending on what you are trying to accomplish withresult.