[英]Why isn't arr[-2] equivalent to -2[arr]?
#include <iostream>
using namespace std;
int main()
{
int arr[3] = { 10, 20, 30 };
cout << arr[-2] << endl;
cout << -2[arr] << endl;
return 0;
}
Output: 输出:
4196160
-30
Here arr[-2]
is out of range and invalid, causing undefined behavior . 这里
arr[-2]
超出范围且无效,从而导致未定义的行为 。 But -2[arr]
evaluates to -30
. 但是
-2[arr]
值为-30
。 Why? 为什么?
Isn't arr[-2]
equivalent to -2[arr]
? arr[-2]
等于-2[arr]
吗?
-2[arr]
is parsed as -(2[arr])
. -2[arr]
被解析为-(2[arr])
。 In C (and in C++, ignoring overloading), the definition of X[Y]
is *(X+Y)
(see more discussion of this in this question ), which means that 2[arr]
is equal to arr[2]
. 在C语言中(以及在C ++中,忽略重载),
X[Y]
的定义为*(X+Y)
(请参阅此问题的更多讨论),这意味着2[arr]
等于arr[2]
。
The compiler parses this expression 编译器解析此表达式
-2
like 喜欢
unary_minus decimal_integer_literal
That is definitions of integer literals do not include signs. 也就是说,整数文字的定义不包括符号。
In turn the expression 反过来表达
2[arr]
is parsed by the compiler as a postfix expression. 由编译器解析为后缀表达式。
Postfix expressions have higher precedence than unary expressions. 后缀表达式的优先级高于一元表达式。 Thus this expression
因此这个表达
-2[arr]
is equivalent to 相当于
- ( 2[arr] )
So the unary minus is applied to the lvalue returned by the postfix expression 2[arr]
. 因此,一元减号将应用于后缀表达式
2[arr]
返回的左值。
On the other hand if you wrote 另一方面,如果你写
int n = -2;
and then 然后
n[arr]
then this expression would be equivalent to 那么这个表达式就相当于
arr[-2]
-2[arr]
is equivalent to -(2[arr])
, which is equivalent to -arr[2]
. -2[arr]
等效于-(2[arr])
,等效于-arr[2]
。 However, (-2)[arr]
is equivalent to arr[-2]
. 但是,
(-2)[arr]
等同于arr[-2]
。
This is because E1[E2] is identical to (*((E1)+(E2))) 这是因为E1 [E2]等于(*((E1)+(E2)))
The underlying problem is with operator precedence . 根本的问题在于运算符的优先级 。 In C++ the
[]
, ie the Subscript operator hold more precedence (somewhat akin to preferance) than the -
unary_minus operator. 在C ++中的
[]
也就是说,下标运算保持更优先级(有些类似于偏好研究)比-
unary_minus运算符。
So when one writes, 所以当一个人写的时候
arr[-2]
The compiler first executes arr[]
then -
, but the unary_minus is enclosed within the bounds of the [-2]
so the expression is decomposed together. 编译器首先执行
arr[]
然后执行-
,但是unary_minus包含在[-2]
的范围内,因此表达式可以分解在一起。
In the, 在里面,
-2[arr]
The same thing happens but, the compiler executes 2[]
first the n the -
operator so it ends up being -(2[arr])
not (-2)[arr]
发生相同的事情,但是编译器首先在
-
运算符中执行2[]
,因此最终结果是-(2[arr])
而不是(-2)[arr]
Your understanding of the concept that, arr[i]
i[arr]
and *(i+arr)
are all the same is correct. 您对
arr[i]
i[arr]
和*(i+arr)
相同的概念的理解是正确的。 They are all equivalent expressions. 它们都是等效的表达式。
If you want to write in that way, write it as (-2)[arr]
. 如果要以这种方式编写,请将其写为
(-2)[arr]
。 You will get the same value for sure. 您肯定会获得相同的值。
Check this out for future referance : http://en.cppreference.com/w/cpp/language/operator_precedence 检查此内容以备将来参考: http : //en.cppreference.com/w/cpp/language/operator_precedence
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.