dereference and advance pointer in one statement?

2019-07-24 15:12发布

问题:

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*)

回答1:

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.



回答2:

id = *i++

will do what you want.

++ modifies the pointer after the dereference.

EDIT: As Eric points out, per the spec, ++ does not happen after dereference. i++ increments i and return its initial value, so the spec defined behavior is the increment happens prior to dereference. The visible behavior of id = *i++ is the same whether you view the increment happening before or after dereference.