Originally Posted by
Saurabh Mehta
.But it is evident that the final value in 'i'(if i=1) would be 3..Can someone please clear my doubt..
It may be evident to you, but the standard (by allowing the behaviour to be undefined) does not mandate anything about how a compiler will interpret that code.
Let's look at the case
(where j is not an alias for i), and j initially has a value of 1.
One interpretation of this is that
1) Value of 1 is stored in register A.
2) Value of j is fetched into register B.
3) Register B is incremented.
4) Value in Register B is added to value in Register A.
5) Value in register A is copied to variable i.
6) Value in Register B is copied to variable j.
This is not the only way it might be done, but this sequence of events is guaranteed to give the required results. The end result is that j has been incremented, and i has a value equal to the original j plus 2.
Now, let's say the compiler does the same thing, except that j is an alias for i. (All I've done in the sequence below is take the sequence above, and substitute i where it referred to j).
1) Value of 1 is stored in register A.
2) Value of i is fetched into register B.
3) Register B is incremented.
4) Value in Register B is added to value in Register A.
5) Value in register A is copied to variable i.
6) Value in Register B is copied to variable i.
(Notice that Step 6 cancels out the effect of Step 5). The end result, if i initially has the value of 1, is that i will have the value of 2.
Now you could argue that the compiler should detect that i and j are aliased, and emit different code. That is not always possible. For example, if in one source file
Code:
void stuff(int *x, int *y)
{
*x = ++(*y) + 1;
}
and in another
Code:
#include <stdio.h>
void stuff(int *, int *);
int main()
{
int i = 1;
stuff(&i, &i);
printf("%d\n", i);
}
the compiler has no way of knowing that x and y point to the same int. Yes, you can detect it. But a compiler is not required to do such error checking for you.