O
Ook
I had a coworker present this problem:
int i = 0;
int j,k;
j = i++ + i++;
k = ++i + ++i;
And asked what j and k will have. I would expect that the compiler would add
i to i (0+0), store the 0 in j, and then increment i twice. On the next
line, we start with i = 2. I is incremented twice so that it now equals 4.
Then it is added to itself (i + i) and the result, 8, is stored in k. I run
it, and it does this. My coworker stated that this was actually undefined
and that you can't read a variable in an expression where you write it. Is
this really undefined and both of my compilers do what I described above
because that is what they wrote the compiler? Or is this functionality the
way c++ should work?
int i = 0;
int j,k;
j = i++ + i++;
k = ++i + ++i;
And asked what j and k will have. I would expect that the compiler would add
i to i (0+0), store the 0 in j, and then increment i twice. On the next
line, we start with i = 2. I is incremented twice so that it now equals 4.
Then it is added to itself (i + i) and the result, 8, is stored in k. I run
it, and it does this. My coworker stated that this was actually undefined
and that you can't read a variable in an expression where you write it. Is
this really undefined and both of my compilers do what I described above
because that is what they wrote the compiler? Or is this functionality the
way c++ should work?