Is this undefined behavior?

I'm having trouble understanding sequence points.

For now, I'd like to know if this below is undefined behavior, and if so, why?

1
2
3
bool flag = true;

flag = !flag;

That should simply toggle the bool. It's used a lot in programs that have buttons.

For instance:

1
2
3
4
5
6
7
8
9
struct Button {
     bool buttonPressed;

     Button( ) { buttonPressed = false; }

     void Click( ) {
          buttonPressed = !buttonPressed;
      }
}
Last edited on
> I'm having trouble understanding sequence points.

You mean Sequenced-before rules. (Sequence point rules were there in C++98)
http://en.cppreference.com/w/cpp/language/eval_order

!flag is a value computation with no side effects. By Rule 2), the value computation of !flag is sequenced before the the value computation of the result of the assignment. Therefore, it has well-defined behaviour.

This is like i = i+1 ; being well-defined.

Topic archived. No new replies allowed.