1

I'm reading an interesting article A Guide to Undefined Behavior in C and C++, Part 1 on undefined behavior in C and C++. Often I do the following in my code:

int i = 10;
i = (++i) % 7;

Does this produce undefined behavior? On x86? ARM? Perhaps it depends on the compiler?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
MrDatabase
  • 43,245
  • 41
  • 111
  • 153

2 Answers2

8

It's undefined behavior because i is modified more than once without an intervening sequence point.

It depends on the compiler only in the sense that there are no requirements about what the code will do, so every compiler can do something different. To be clear - just because even though you get results that seem to make sense (sometimes), the code is a bug.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Michael Burr
  • 333,147
  • 50
  • 533
  • 760
1

Yes - as per standard ISO C.

Though, a compiler is expected to produce consistent result.

Community
  • 1
  • 1
YetAnotherUser
  • 9,156
  • 3
  • 39
  • 53
  • 2
    A compiler is not expected to produce anything consistent - you could most certainly get different results on different runs of code with undefined behavior. That might be somewhat unlikely with this particular UB, but there are no expectations nonetheless. – Michael Burr May 14 '11 at 03:03
  • @Michael thanks for pointing, I stand corrected. Will include more details in the answer. – YetAnotherUser May 14 '11 at 03:11