I came across the following code on geeksquiz.com but could not understand how the expressions involving prefix, postfix and dereference operators are evaluated in C:
#include <stdio.h>
#include <malloc.h>
int main(void)
{
int i;
int *ptr = (int *) malloc(5 * sizeof(int));
for (i=0; i<5; i++)
*(ptr + i) = i;
printf("%d ", *ptr++);
printf("%d ", (*ptr)++);
printf("%d ", *ptr);
printf("%d ", *++ptr);
printf("%d ", ++*ptr);
free(ptr);
return 0;
}
The output is given as :
0 1 2 2 3
Can somebody please explain how this is the output for the above code?
The precedence of operators in C can be found here.
In your example, the only expression where precedence matters is this one:
Here, postfix operator
++
has higher precedence, so it is equivalent toThere is no possible ambiguity in the rest (
(*ptr)++
,*ptr
,*++ptr
and++*ptr
.) You seem to be confused by the semantics of the pre- and postfix++
operators. Bear in mind that sometimes you increment the pointer, others the thing it points to. This is what happens: