Why is i = v[i++] undefined?

后端 未结 8 1476
生来不讨喜
生来不讨喜 2021-02-01 13:41

From the C++ (C++11) standard, §1.9.15 which discusses ordering of evaluation, is the following code example:

void g(int i, int* v) {
    i = v[i++]; // the beha         


        
8条回答
  •  礼貌的吻别
    2021-02-01 13:57

    The reason is not just historical. Example:

    int f(int& i0, int& i1) {
        return i0 + i1++;
    }
    

    Now, what happens with this call:

    int i = 3;
    int j = f(i, i);
    

    It's certainly possible to put requirements on the code in f so that the result of this call is well defined (Java does this), but C and C++ don't impose constraints; this gives more freedom to optimizers.

提交回复
热议问题