Monday, May 30, 2011

The riddle of n = n++ ???

What would be the result of


int n = 0;
for( int m = 0; m < 5; m++){
   n = n++;
   print(n);
}

Well, even i had been confused. Later with lots of discussions, I have concluded that it is compiler dependent.

Lets look at JAVA first.
In java, while executing the statement
n = n++
what actually happens is, an intermediate variableis created. It stores the original value of n. so the sequence is

temp = n;
n++;
n = temp;

Thus in JAVA, the output is
0 0 0 0 0


Now lets look at C and C++.
In these compilers, there is Direct Memory Operations with Pointers without the use of intermediate variables.

So the result in this case is what many people would expect. That is
1 2 3 4 5