Search code examples
coperatorsoperator-precedenceunary-operatorpostfix-operator

Having trouble understanding pointer operations


I can't exactly understand what the language does when I write

*(t++)

*t++

When t is a pointer?


Solution

  • These two expressions

    *(t++)
    
    *t++
    

    are equivalent due to the operator precedence.

    So the postfix operator ++ has a higher priority than the unary operator *.

    The result of the postfix operator ++ is the value of its operand before incrementing.

    From 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)....

    Take into account that due to the pointer arithmetic if you have a pointer like this

    T *p;
    

    where T is some type then after the operation p++ the final value of the pointer itself is incremented by the value sizeof( T ). For the type char sizeof( char ) is always equal to 1.

    Consider the following demonstrative program.

    #include <stdio.h>
    
    int main(void) 
    {
        char *t = "AB";
    
        printf( "%c\n", *t++ );
        printf( "%c\n", *t );
    
        return 0;
    }
    

    Its output is

    A
    B
    

    You can substitute this statement

    printf( "%c\n", *t++ );
    

    for this statement

    printf( "%c\n", *( t++ ) );
    

    and you will get the same result.

    In fact this expression

    *(t++)
    

    is also equivalent to the expression

    t++[0]