gpt4 book ai didi

c++ - 我在哪里可以找到标准中对 *p 和 p[0]、*(p+1) 和 p[1]、... 之间等价关系的引用?

转载 作者:行者123 更新时间:2023-11-27 22:56:06 28 4
gpt4 key购买 nike

在下面的代码片段中,符号 *p 等同于 p[0]*(p + 1) 等同于p[1],依此类推。

int* p = new int[3] { 1, 2, 3};
cout << *p << ' ' << *(p + 1) << ' ' << *(p + 2) << '\n';
cout << p[0] << ' ' << p[1] << ' ' << p[2] << '\n';

我可以在标准中的什么地方找到对这种等效性的引用?

最佳答案

这包含在 C++14 标准草案第 5.2.1 节下标 [expr.sub](强调我的):

A postfix expression followed by an expression in square brackets is a postfix expression. One of the expressions shall have the type “array of T” or “pointer to T” and the other shall have unscoped enumeration or integral type.[...] The expression E1[E2] is identical (by definition) to *((E1)+(E2)) [ Note: see 5.3 and 5.7 for details of * and + and 8.3.4 for details of arrays. —end note ],

本段引用了 5.3 部分的 *,它说:

The unary * operator performs indirection: the expression to which it is applied shall be a pointer to an object type, or a pointer to a function type and the result is an lvalue referring to the object or function to which the expression points. If the type of the expression is “pointer to T,” the type of the result is “T.”[...]

5.7 部分 + 说:

When an expression that has integral type is added to or subtracted from a pointer, the result has the type of the pointer operand. [...] if the expression P points to the i-th element of an array object, the expressions (P)+N (equivalently, N+(P)) and (P)-N (where N has the value n) point to, respectively, the i + n-th and i − n-th elements of the array object, provided they exist[ ...]

关于c++ - 我在哪里可以找到标准中对 *p 和 p[0]、*(p+1) 和 p[1]、... 之间等价关系的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32906247/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com