-1

When building a program using a newer version of GCC, I found a problem in the code.

count[i] = count[i]++;

This code worked with an older version of GCC (2.95), but doesn't work with a newer version (4.8).

So I suspect this statement causes undefined behaviour, am I correct? Or is there a better term for this problem?

rcr
  • 13
  • 2
  • Gcc is a C compiler. Is your question about C++ or C? – DYZ Oct 26 '18 at 03:07
  • @DYZ Well, "GCC" can also be the name of a software suite that contains both C compiler and C++ compiler with many things else... –  Oct 26 '18 at 03:09
  • This question is about C++, but if there is any difference with C regarding this problem I would like to know that too. – rcr Oct 26 '18 at 03:11

2 Answers2

1

Indeed, this is undefined behavior.

int i = 2;
i = i++; // is i assigned to be 2 or 3?
ChilliDoughnuts
  • 367
  • 2
  • 13
  • According to operator precedence, `i++` will be evaluated first, then assignment, so it will be assigned 3. https://en.cppreference.com/w/c/language/operator_precedence although this may vary depending on the std= – awiebe Oct 26 '18 at 03:16
  • 3
    @awiebe Operator precedence isn't the same thing as [order of evaluation](https://en.cppreference.com/w/cpp/language/eval_order). This code is undefined behavior until C++17. – Blastfurnace Oct 26 '18 at 03:23
  • @awiebe The issue is not when `i++` is evaluated but when the increment takes place. The result will be different if the increment takes place after the assignment versus if the increment takes place before the assignment. The increment is distinct from evaluation. This code writes both 2 and 3 to `i` and nothing requires either write to occur first (until C++ 17). – David Schwartz Oct 26 '18 at 03:38
  • @awiebe gcc 4.7.4 returns i=3 and gcc 4.8.1 returns i=2. – Jerry Jeremiah Oct 26 '18 at 04:08
1

This is actually specified as undefined behavior as each compiler defines its own order of operation as stated on: https://en.cppreference.com/w/cpp/language/eval_order

Order of evaluation of the operands of almost all C++ operators (including the order of evaluation of function arguments in a function-call expression and the order of evaluation of the subexpressions within any expression) is unspecified. The compiler can evaluate operands in any order, and may choose another order when the same expression is evaluated again.

There is actually a warning on the increment/decrement page in the cppreference: https://en.cppreference.com/w/cpp/language/operator_incdec

Because of the side-effects involved, built-in increment and decrement operators must be used with care to avoid undefined behavior due to violations of sequencing rules.

Patrick
  • 375
  • 3
  • 12