views:

179

answers:

2

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

+2  A: 

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.

Daniel LeCheminant
+2  A: 

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.

Michael
Actually, you have to be really careful when making that statement. It APPEARS that the pointer is modified after the dereference, but that is not actually true! Remember, "after" implies that there is a _sequence of events in time_. It is character building to work out what the exact sequence of events in time is for this case. When you do so, you'll see that in fact the variable modification happens BEFORE the dereference.
Eric Lippert