Search code examples
c#operator-precedenceunsafe-pointers

dereference and advance pointer in one statement?


I'm reading from a byte array as follows:

int* i = (int*)p;
id = *i;
i++;

correct me if I'm wrong, but ++ has precedence over *, so is possible to combine the *i and i++ in the same statement? (e.g. *i++)

(this is technically unsafe C#, not C++, p is a byte*)


Solution

  • I believe that

    id = *i;
    i++;
    

    and

    id = *i++;
    

    are equivalent.

    The ++ operator, when used as a suffix (e.g. i++), returns the value of the variable prior to the increment.


    I'm somewhat confused by the reflector output for

    unsafe class Test
    {
        static public void Test1(int p, out int id)
        {
            int* i = (int*)(p);
            id = *i;
            i++;
        }
    
        static public void Test2(int p, out int id)
        {
            int* i = (int*)(p);
            id = *i++;
        }
    }
    

    which comes out as

    public static unsafe void Test1(int p, out int id)
    {
        int* i = (int*) p;
        id = i[0];
        i++;
    }
    

    and

    public static unsafe void Test2(int p, out int id)
    {
        int* i = (int*) p;
        i++;
        id = i[0];
    }
    

    which clearly are not equivalent.