问题描述
正如 Joel 在 Stack Overflow 播客 #34 中指出的那样,C 编程语言(又名:K & R),有提到这个C 中数组的属性:a[5] == 5[a]
As Joel points out in Stack Overflow podcast #34, in C Programming Language (aka: K & R), there is mention of this property of arrays in C: a[5] == 5[a]
Joel 说是因为指针运算,但我还是不明白.为什么a[5] == 5[a]
?
Joel says that it's because of pointer arithmetic but I still don't understand. Why does a[5] == 5[a]
?
推荐答案
C 标准定义了 []
操作符如下:
The C standard defines the []
operator as follows:
a[b] == *(a + b)
因此 a[5]
将评估为:
*(a + 5)
和 5[a]
将评估为:
*(5 + a)
a
是指向数组第一个元素的指针.a[5]
是距离 a
5 元素 的值,与 *(a + 5),从小学数学我们知道它们是相等的(加法是可交换).
a
is a pointer to the first element of the array. a[5]
is the value that's 5 elements further from a
, which is the same as *(a + 5)
, and from elementary school math we know those are equal (addition is commutative).
这篇关于对于数组,为什么会出现 a[5] == 5[a]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!