-
pre/Post Increment
from below Snippet, how i value is calculated??
Code:
1)
int i = 2;
int k = i++ - i++;
printf("%d %d",k i);
o/p I m getting ---> k = 0, i = 3
My doubt is ++ operator has R - L evaluation , here am doing
post incerement so first expression would be evaluated with original value
nd next value will get incremented twice so i value is 4.
but am getting i value is 3 ???
2)
Code:
int i = 2;
int k = ++i - ++i;
printf("%d %d",k,i);
o/p i m getting ----> k = -1, i = 4
Here am doing preincrement so first value will get incremented nd
next expression will be evaluated .My doubt is 3 - 4 or 4 - 3 ?? first
which variable will get incremented??(left side or right side).
Could u plz clarify it....
-
Both of your cases are undefined, as the C standard does specifically says [something like] "no variable must be updated twice within the same sequence point". Since a sequence point is roughly the same as a statement [there are places where it isn't, but we'll ignore that for now], your breaks that rule.
What actually happens is that the compiler will order the increement of i and subtract independently of each other, which means that it may do:
Code:
k = i - i;
i++;
i++;
or
Code:
i++;
k = i (i++;) - i; // Not C syntax! It does i++ after taking the first value of i.
And likewise for the ++i variant.
Finally, in theory, the compiler is perfectly allowed to come up with ANY numeric answer - the fact that you are getting some sort of reasonable answer is entirely based on the compiler doing "something sensible", but it's not guaranteed to do that.
--
Mats