What is the explanation for the output of the following C program?

696 Views Asked by At

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?

1

There are 1 best solutions below

5
On BEST ANSWER

The precedence of operators in C can be found here.

In your example, the only expression where precedence matters is this one:

*ptr++

Here, postfix operator ++ has higher precedence, so it is equivalent to

*(ptr++)

There 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:

printf("%d ", *ptr++);   // Increment pointer, de-reference old value: 0
printf("%d ", (*ptr)++); // De-reference pointer, increment, yield old value
                         // Evaluates to 1, sets *ptr to 2
printf("%d ", *ptr);     // De-reference ptr, yields 2 (see above)
printf("%d ", *++ptr);   // Increment ptr, de-reference: 2
printf("%d ", ++*ptr);   // De-reference (2), increment result: 3