I've been told that when we write int a[100] = {1};
, the elements after 1
will be initialized to 0. But I didn't find out how this is done. (And is this true?)
I've tried the code below to roughly find out the time cost:
#define M 500000
clock_t begin = clock();
int main(){
/*-1-*/ //int a[M] = {1};
/*-2-*/ //int a[M]; memset(a, 0, sizeof(int) * M);
/*-3-*/ //int a[M]; for(int i = 0; i < M; i++) a[i] = 0;
clock_t end = clock();
cout<<(double) (end - begin) / CLOCKS_PER_SEC<<endl;
return 0;
}
Where -1- to -3- is the 3 cases tested. Each time I use one of them. On my computer, the average time of the first 2 cases is 0.04, and the 3rd case costs 0.08 (Each tested for 10 times). So I guess the initialization is done like memset
?
But I'm still confused whether these two are the same. If so, who is doing this?
Please excuse me for my poor English.
Thanks for the comments! And I've read the references and the linked questions. I've make it clear that the compiler does make the remainder elements to 0, but how is this done in lower level... maybe assembly? I'm sorry I didn't find references about that.
I'm new to stackoverflow, should I just edit my question like this?
Update:
Thanks a lot! I think I'm clear now.
The standard says when I int a[100] = {1};
, the rest will be left 0
. So my compiler will use some method to implement this, and different compiler may do this in different way. (Thank @eerorika to let me understand this!)
And thank @john for the site godbolt.org where I can read the assembly produced easily. Here I find out in x86-64 gcc 10.2(although in C but not C++), int a[100] = {1};
behaves like:
leaq -400(%rbp), %rdx
movl $0, %eax
movl $50, %ecx
movq %rdx, %rdi
rep stosq
movl $1, -400(%rbp)
movl $0, %eax
It use stosq
to save 0's every quad-words for 50 times, which equals to 2 int
to initialize the array.
And thank @largest_prime_is_463035818 to let me know my mistake in measuring time.
Thank all you for making me clear!