1

I am having a pretty basic C++ problem, and I really dont get why I have that Problem... So thats my function:

void build(int *&v) {
    v = new int[m];
    for (int i =0; i<m;){
         v[i]=i++;
    }
    for (int i=0;i<m;i++){
        cout <<i << " " << v[i] <<endl;
    }

I would expect to get an output like

0 0
1 1
2 2

since i is always incrementet after processing. So i is =0 first -> 0 0 then its incrementet to 1, which leads to 1 1 and then its incrementet to 2 which leads to 2 2

But my console always gives me

0 0
1 0
2 1

Where is my fault?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Hball99
  • 485
  • 1
  • 4
  • 4
  • 7
    `v[i]=i++;` is *undefined behavior* before C++17 – UnholySheep Jan 19 '19 at 11:21
  • 1
    Why do you expect `v[i]` to be evaluated before `i++`? To do the assignment, `i++` must be evaluated to know what to store and `v[i]` must be evaluated to know where to store it. You expect `v[i`] to be evaleated before `i++`. Why? – David Schwartz Jan 19 '19 at 11:22
  • 4
    the actual problem is that you didnt write `for(int i=0;i – 463035818_is_not_an_ai Jan 19 '19 at 11:23
  • well no i am not trying to be fancy.. i am learning for an uni exam and that was an actual question in an exam of last year to predict the console output... – Hball99 Jan 19 '19 at 11:33
  • @DavidSchwartz i thought v[i] would be evaluated first because its written first.. so v[0] = 0, i++-> v[1]=1, i++-> v[2]=2.. where am i missing the point? – Hball99 Jan 19 '19 at 11:40
  • 1
    @Hball99 There is no C++ rule that says that sub-expressions are evaluated in the order they're written. So your fault was thinking there was such a rule. – David Schwartz Jan 19 '19 at 12:15
  • then its not you but the code that tries to be fancy, still such code is only good for trick questions but shouldnt pass a code review imho – 463035818_is_not_an_ai Jan 19 '19 at 13:56

0 Answers0