C99语法之按元素下标赋值

  C语言C99标准中出现了一些比较奇葩的语法,比如说使用元素下标的方式了对数组进行初始化这种操作 Demo如下:

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 
 4 int main(int argc, char **argv)
 5 {
 6     int arr[] = { [0] = 1, [1] = 2, [2] = 3, [15] = 10 };//按照元素赋值
 7 
 8     printf("%d\n",sizeof(arr));
 9 
10     getchar();
11     return 0;
12 }

C99 中支持了这种形式的数组初始化,这段代码的执行结果是

这说明这个数组有16个int。

其反汇编的结果如下:

 1     int arr[] = { [0] = 1, [1] = 2, [2] = 3, [15] = 10 };//按照元素赋值
 2 00D513DE  mov         dword ptr [arr],1  
 3 00D513E5  mov         dword ptr [ebp-40h],2  
 4 00D513EC  mov         dword ptr [ebp-3Ch],3  
 5 00D513F3  mov         dword ptr [ebp-38h],0  
 6 00D513FA  mov         dword ptr [ebp-34h],0  
 7     int arr[] = { [0] = 1, [1] = 2, [2] = 3, [15] = 10 };//按照元素赋值
 8 00D51401  mov         dword ptr [ebp-30h],0  
 9 00D51408  mov         dword ptr [ebp-2Ch],0  
10 00D5140F  mov         dword ptr [ebp-28h],0  
11 00D51416  mov         dword ptr [ebp-24h],0  
12 00D5141D  mov         dword ptr [ebp-20h],0  
13 00D51424  mov         dword ptr [ebp-1Ch],0  
14 00D5142B  mov         dword ptr [ebp-18h],0  
15 00D51432  mov         dword ptr [ebp-14h],0  
16 00D51439  mov         dword ptr [ebp-10h],0  
17 00D51440  mov         dword ptr [ebp-0Ch],0  
18 00D51447  mov         dword ptr [ebp-8],0Ah  


C89支持的写法:

 1     int ar[15] = { 1, 2, 3, 4, 5, 6, 7, 8 };
 2 000F3D3E  mov         dword ptr [ar],1  
 3 000F3D48  mov         dword ptr [ebp-84h],2  
 4 000F3D52  mov         dword ptr [ebp-80h],3  
 5 000F3D59  mov         dword ptr [ebp-7Ch],4  
 6 000F3D60  mov         dword ptr [ebp-78h],5  
 7     int ar[15] = { 1, 2, 3, 4, 5, 6, 7, 8 };
 8 000F3D67  mov         dword ptr [ebp-74h],6  
 9 000F3D6E  mov         dword ptr [ebp-70h],7  
10 000F3D75  mov         dword ptr [ebp-6Ch],8  
11 000F3D7C  xor         eax,eax  
12 000F3D7E  mov         dword ptr [ebp-68h],eax  
13 000F3D81  mov         dword ptr [ebp-64h],eax  
14 000F3D84  mov         dword ptr [ebp-60h],eax  
15 000F3D87  mov         dword ptr [ebp-5Ch],eax  
16 000F3D8A  mov         dword ptr [ebp-58h],eax  
17 000F3D8D  mov         dword ptr [ebp-54h],eax  
18 000F3D90  mov         dword ptr [ebp-50h],eax


因此这两者上只是语法上的不同,却没有本质上什么差别。

                                                       by:ECN14

 

posted on 2014-12-09 18:44  ECN14  阅读(412)  评论(0编辑  收藏  举报

导航