1
#include <iostream>
#include <vector>

using namespace std;

int main()
{
    vector<int> v{1,2,3,4,5};
    int i = 0;
    while (i < 5) {
        cout << i+v[i++] << endl;
    }

    return 0;
}

Why the output of the program is "2,4,6,8,10", instead of "1,3,5,7,9"?

LacticAcid
  • 21
  • 2
  • 1
    `Why the output of the program is "2,4,6,8,10", instead of "1,3,5,7,9"` Undefined behavior. – kiran Biradar Oct 23 '18 at 08:02
  • 2
    To expand on what @kiranBiradar says, you *aren't allowed* to do this expression. It'll compile, but the compiler can do whatever it wants. It'll probably try to do something sensible, but it might not be a good judge what "sensible" is, so you should avoid undefined behavior in almost all cases. – Daniel H Oct 23 '18 at 08:06
  • @DanielH Thanks for your extended explanation! – LacticAcid Oct 23 '18 at 23:17

2 Answers2

5

This is undefined behaviour because the read of the "first" i and the other i++ are unsequenced. The output is meaningless.

Further reading: Undefined behavior and sequence points,

M.M
  • 138,810
  • 21
  • 208
  • 365
5

Some compilers will warn you that you are doing something that leads to undefined behavior: Relying on the evaluation order of unsequenced expressions.

Example:

<source>:22:22: warning: unsequenced modification and access to 'i' [-Wunsequenced]
   cout << i+v[i++] << endl;

The evaluation order of expressions between sequence points is not defined. The only sequence point in the expression i+v[i++] is at the end of the expression, so the compiler is free to order the addition of i and the increment of i however it wants.

Max Langhof
  • 23,383
  • 5
  • 39
  • 72