Are pointer variables just integers with some operators or are they “symbolic”?

后端 未结 4 1542
长情又很酷
长情又很酷 2020-11-28 15:40

EDIT: The original word choice was confusing. The term \"symbolic\" is much better than the original (\"mystical\").

In the discussion about my previous C++ questio

4条回答
  •  死守一世寂寞
    2020-11-28 16:13

    Stealing the quote from TartanLlama:

    [expr.add]/5 "[for pointer addition, ] if both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined."

    So the compiler can assume that your pointer points to the a array, or one past the end. If it points one past the end, you cannot defererence it. But as you do, it surely can't be one past the end, so it can only be inside the array.

    So now you have your code (reduced)

    b = 1;
    *pa1 = 2;
    

    where pa points inside an array a and b is a separate variable. And when you print them, you get exactly 1 and 2, the values you have assigned them.

    An optimizing compiler can figure that out, without even storing a 1or a 2 to memory. It can just print the final result.

提交回复
热议问题