-1

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;
}
alk
  • 69,737
  • 10
  • 105
  • 255
  • @JoachimPileborg ok retracting the close vote here -- you're right in this case, the prefix ++ binds to the dereferenced ptr. Just adding ... why the hell write such code? But ok, let's say it's a lab example or something like this ... –  Oct 25 '15 at 14:24
  • @MartinJames: Not really ... – alk Oct 25 '15 at 14:26
  • Just adding I really had to put parenthesis manually (like Joachim did in his answer) to understand it's *not* the same memory location modified by the two `++` in this example. It's definitely code nobody would ever want to see in "production". :) –  Oct 25 '15 at 14:31
  • 1
    Possible duplicate of [Precedence and associativity of prefix and postfix in c](http://stackoverflow.com/questions/27276159/precedence-and-associativity-of-prefix-and-postfix-in-c). Similarly, [precedence of ++ (post,prefix) nd dereference operator](http://stackoverflow.com/questions/16775012/precedence-of-post-prefix-nd-dereference-operator) – Spikatrix Oct 25 '15 at 15:54

1 Answers1

3

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)
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621