Search code examples
cassociativity

Please explain the associativity of the operators in this code


#include <stdio.h>
int main(void)
{
  char s[] = {'a','b','c','\n','c','\0'};
  char *p;
  p=&s[3];
  printf("%d\t",++*p++);
  printf("%d",*p);
  return 0;
}  

output: 11 99
Please explain the output. Why there is an increment in the address?


Solution

  • The only thing I see that could possibly be confusing is

    ++*p++
    

    Postincrement has higher precedence than the dereference operator, so fully parenthesized it looks like

    ++(*(p++))
    

    Which postincrements p, dereferences the original value of p to get a char, then preincrements the value of the char, and then the new value gets printed by printf as an integer.

    So both p and what p is pointing at get incremented.