Hi Everyone,
I have the following code,
int main()
{
int p[] = {10,20,30,40,50};
int *i = &p[0];
printf("before : %p\n",(void*)i);
printf("1 %d %d\n",*++i,*i++);
printf("after : %p\n",(void*)i);
}
As per my understanding, arguements to a function call are
passed from right most to left most one,
In C, it isn't specified how arguments are passed (but this isn't
actually relevent to the behavior you've observed).
so in this case *i++ will be processed first and then *++i,
The order in which function arguments are evaluated is unspecified,
relative to each other. All that matters is that all the necessary
evaluation occurs at some point prior to the function call; this is
an example of a "sequence point". In your code above, the relevent
sequence points are at the semicolon after the first printf (that is,
after the first printf call is complete) and the parentheses of the
second printf (that is, at the instant of the second printf call).
The idea of sequence points leads naturally to some restrictions
as to what you can legally do between them. An important one is
that you can't use ++ twice on the same object and expect the
result to be meaningful (think about it). This is an example of
"undefined behavior"; technically you can rely on nothing, or
alternately anything at all, to happen when you have undefined
behavior in your program. In other words: Don't Do That.
hence i expect the output to be
1 30 10
where as the output is
1 20 10
Can anybody explain as to why this is happening?
I probably could, but I won't, because the program has undefined
behavior, so anything is fair game. Oops, I guess that explained it.
I will however note that in the expression *i++, the increment only
has to occur somewhere before the next sequence point, but it's
not specified exactly where. (Both outputs above suggest certain
obvious, unoptimized, instruction sequences. Using a different set
of optimization settings on your compiler may result in a different
output. Or it might make your program crash, or scribble on your
hard drive.)