0

Possible Duplicate:
Undefined Behavior and Sequence Points

The variable i is changed twice, but is the next example going to cause an undefined behaviour?

#include <iostream>
int main()
{
    int i = 5;
    std::cout << "before i=" << i << std::endl;
    ++ i %= 4;
    std::cout << "after i=" << i << std::endl;
}

The output I get is :

before i=5
after i=2
Community
  • 1
  • 1
BЈовић
  • 62,405
  • 41
  • 173
  • 273

1 Answers1

7

Yes, it's undefined. There is no sequence point on assignment, % or ++ And you cannot change a variable more than once within a sequence point.

A compiler could evaluate this as:

++i;
i = i % 4;

or

i = i % 4;
++i;

(or something else)

Habalusa
  • 1,770
  • 3
  • 15
  • 15