I'm learning C++ from basics (using Visual Studio Community 2015)
While working on the arrays I came across the following:
int main()
{
int i[10] = {};
}
The assembly code for this is :
18: int i[10] = {};
008519CE 33 C0 xor eax,eax
008519D0 89 45 D4 mov dword ptr [ebp-2Ch],eax
008519D3 89 45 D8 mov dword ptr [ebp-28h],eax
008519D6 89 45 DC mov dword ptr [ebp-24h],eax
008519D9 89 45 E0 mov dword ptr [ebp-20h],eax
008519DC 89 45 E4 mov dword ptr [ebp-1Ch],eax
008519DF 89 45 E8 mov dword ptr [ebp-18h],eax
008519E2 89 45 EC mov dword ptr [ebp-14h],eax
008519E5 89 45 F0 mov dword ptr [ebp-10h],eax
008519E8 89 45 F4 mov dword ptr [ebp-0Ch],eax
008519EB 89 45 F8 mov dword ptr [ebp-8],eax
Here, since initalisation is used every int here is initialised to 0 (xor eax,eax). This is clear.
From what I have learnt, any variable would be allocated memory only if it is used (atleast in modern compilers) and if any one element in an array is initialised the complete array would be allocated memory as follows:
int main()
{
int i[10];
i[0] = 20;
int j = 20;
}
Assembly generated:
18: int i[10];
19: i[0] = 20;
00A319CE B8 04 00 00 00 mov eax,4
00A319D3 6B C8 00 imul ecx,eax,0
00A319D6 C7 44 0D D4 14 00 00 00 mov dword ptr [ebp+ecx-2Ch],14h
20: int j = 20;
00A319DE C7 45 C8 14 00 00 00 mov dword ptr [ebp-38h],14h
Here, the compiler used 4 bytes (to copy the value 20
to i[0]
) but from what I have learnt the memory for the entire array should be allocated at line 19
. But the compiler haven't produced any relevant machine code for this. And where would it store info (stating that the remaining memory for the other nine elements[1-9] of array i's
cannot be used by other variables)
Please help!!!