本文首发于 ❄️慕雪的寒舍
数组竟然还可以这样调用?只能说慕雪学艺不精了!
上代码!
起因是群里的一个图,本来以为只是个开玩笑的bug图,谁知道其他群友说了,我才发现是自己毛都不懂
代码就大概是下面这样,请问你的第一印象,这个代码是否有语法错误呢?
#include <stdio.h>
int main()
{
int a[10] = {1,3,4,5,6,7};
printf("%d ",a[4]);
printf("%d\n",4[a]);
return 0;
}
问题肯定是第二个printf
中的4[a]
,直接上编译运行结果,可以看到不但没有出错,二者的打印的数据也完全相同
[muxue:~/code/c/c_cpp]$ gcc test.cpp -o test
[muxue:~/code/c/c_cpp]$ ./test
6 6
为啥?
如果你对C语言的指针有过了解,应该知道a[n]
实际上在访问的时候,会被转成 *(a+n)
来访问具体的地址
既然是这样,那我们把a和n的顺序倒过来,访问的不就是 *(n+a)
了吗?
学过加法交换律的都知道,这两个访问的结果肯定是相同的
所以这个代码是没有语法错误的,只不过看着很让人迷惑而已。
不过,要是真有人在实际项目里面这样写代码,那就可以去“问候”一下他了。代码可读性极低。
顺带一提
C++中的操作符[]
的重载是不支持你这么玩的哦!因为和operator[]
函数的参数的顺序不一样了
#include <stdio.h>
#include <vector>
using namespace std;
int main()
{
vector<int> a = {1,3,4,5,6,7};
printf("%d ",a[4]);
printf("%d\n",4[a]);//err
return 0;
}
编译报错
[muxue:~/code/c/c_cpp]$ g++ test.cpp -o test
test.cpp: In function ‘int main()’:
test.cpp:10:20: error: no match for ‘operator[]’ (operand types are ‘int’ and ‘std::vector<int>’)
printf("%d\n",4[a]);
^