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

标签 c++ language-lawyer c++14

在下面的代码片段中,符号 *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/

相关文章:

c++ - 作为非类型模板参数的类模板实例的语法

c++ - 在模板类中定义的枚举上嵌套类的部分特化

C++ 不允许堆栈实例但允许新的删除

c++ - Visual Studio 2010 : C/C++ global include and lib folder

c++ - doxygen 正在生成空文档

c++ - std::forward_list::remove_if 谓词的要求

c++ - 使用 Nginx HTTP 解析器的 API

c++ - Constexpr 行列式(二维 std::array)

c++ - 使用循环停止 QThread 的正确方法(从 opencv 读取视频)

c++ - 使用 reinterpret_cast 访问类似 "struct {double, int}"的对象