Search code examples
clanguage-lawyeroperator-precedence

Explanation of output of a C program


The following program gives output:

hffltgpshfflt

Can somebody explain this how does operator precedence of postfix++,prefix++ and dereference(*) operators decide this output?

#include<stdio.h>
int main()
{
  char arr[]  = "geeksforgeeks";
  char *ptr  = arr;

  while(*ptr != '\0')
   ++*ptr++;
  printf("%s %s", arr, ptr);

  getchar();
  return 0;
}

Solution

  • It's easy once one learn the operator precedence and associativity rules.

    You expression ++*ptr++ is equivalent to ++*(ptr++) which is equivalent to ++(*(ptr++)).

    So the order of operations is

    1. The post-increment operator (which returns the old value of the pointer ptr)
    2. The dereferencing of the pointer ptr (before the pointer is incremented)
    3. The prefix-increment of the result of the dereference, increasing the value pointed to by ptr, turning e.g. 'g' to 'h' etc.
    4. The pointer ptr is incremented (actually part of step 1)