what is the difference between the two

there is a lot of difference !!
suppose you do

int array[100] = {-1};

you expect this line to initialize all array elements with -1
but it will not .

this set the first element to -1 and the rest to 0 , since all omitted elements are set to 0 if you specify at least one.

to set them all to -1, you can use something like std::fill_n

std::fill_n(array, 100, -1);

whereas memset will show the expected behaviour .

see this stackoverflow

let me explain this to you in detail .

int arr[n]={0};
this will set all elements to zero .

Elements with missing values will be initialized to 0:

ex :-

int myArray[10] = { 1, 2 }; // initialize to 1,2,0,0,0…

So this will initialize all elements to 0:

int myArray[10] = { 0 }; // all elements 0

In C++, an empty initialization list will also initialize every element to 0. This is not allowed with C:

int myArray[10] = {}; // all elements 0 in C++

Remember that objects with static storage duration will initialize to 0 if no initializer is specified:

static int myArray[10]; // all elements 0

so using the above is better and more portable than memset().

4 Likes