Search code examples
cpointersoperator-precedencepost-incrementpre-increment

Pre / Post increment operator on structure pointer


I'm new to C
didn't get what going on here

struct person {
    int age;
};

main ()
{
    struct person p , *ptr;
    ptr = &p;

  printf ("%d \n" , ++ptr->age );
  printf("%d" , ptr++->age);

  return 0;
}

How Both printf statements prints 1 ?


Solution

  • This expression

    ++ptr->count;
    

    is equivalent to

    ++( ptr->count );
    

    So it increases data member count of the structure pointed to by ptr.

    operator -> in expression ++ptr->count is a postfix operator that has higher priority than any unary operator including pre-increment operator ++.

    In this expression

    ptr++->count;
    

    there are two postfix operators: post-increment operator ++ and operator ->. They are evaluated left to right. The value of the post-increment operator ++ is the value of its operand before incrementing. So this expressions returns the value of data member count of the structure pointed to by ptr before its incrementing. The pointer itself is incremented.

    According to the C Standard (6.5.2.4 Postfix increment and decrement operators)

    2 The result of the postfix ++ operator is the value of the operand. As a side effect, the value of the operand object is incremented (that is, the value 1 of the appropriate type is added to it)....