dereference and advance pointer in one statement?

南楼画角 提交于 2019-12-24 05:58:10

问题


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.



来源:https://stackoverflow.com/questions/1094333/dereference-and-advance-pointer-in-one-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!