hi guys

is it timeconsuming to use memset instead of for?

i mean suppose we have an array of int

int prime[200000];

we use memeset(prime, 200000, 0, sizeof(prime))

also we can use
for(i = 0; i < 200000; i++)
prime = 0;

If either method is faster, it will be memset(). memset() is a compiler provided function, and it might use tricks to run as fast as possible on the target platform.

hi guys

is it timeconsuming to use memset instead of for?

i mean suppose we have an array of int

int prime[200000];

we use memeset(prime, 200000, 0, sizeof(prime))

also we can use
for(i = 0; i < 200000; i++)
prime = 0;

I would expect memset() to be optimized for the machine it was compiled on...

Use memset() to initialize a block of memory to a specified value.
Because this function can use only a type char as the initialization value, it is not useful for working with blocks of data types other than type char, except when you want to initialize to 0.
In other words, it wouldn't be efficient to use memset() to initialize an array of type int to the value 99, but you could initialize all array elements to the value 0.

Perhaps a more interesting question is why you have a 200000-element array that needs initializing in the first place.

If you want to initialize the array to 0 then just declare it like this: int prime[200000] = {0}; and the compiler will most likely use the optimal way to initialize it.

Actually for an array with program lifetime (i.e. one not declare in a function or declared static in a function) you don't even need the = {0} . The compiler initialises all such arrays and variables to 0 if no other value is given.

>>Actually for an array with program lifetime
i.e. global variables. And you are right about that.

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.