If you want to set an entire array to -1 is better to cycle through it with a for loop like this?

for (int i = 0; i < 100; ++i){
  array[i] = -1;
}

Or use memset like this?

memset (array,-1,100);

It rather depends on the type of the array. If it's anything but some variant of char, I'd recommend using a loop to avoid nasties by diddling with individual bytes of a multi-byte type.

void* memset( void* dest, int ch, std::size_t count );
Converts the value ch to unsigned char and copies it into each of the first count characters of the object pointed to by dest.

This means that if your destination can´t be looked as unsigned chars, memset will not work. For example:

#include <iostream>
#include <cstring>

int main()
{
    int a[20];
    std::memset(a, 0, sizeof(a));     /* Note 0 */
    for (int ai : a) std::cout << ai;
}

will work; but:

#include <iostream>
#include <cstring>

int main()
{
    int a[20];
    std::memset(a, 2, sizeof(a));     /* Note 2 */
    for (int ai : a) std::cout << ai;
}

will not!

In conclusion, if you can use memset, it is better because it is faster. The trick is hiden in the words: if you can use. In the case of -1, you can use memset. However, for clarity and if the speed is not an issue, I adhere to the recommendation of deceptikon.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.