7

I have an array of int and i have to initialize this array with the value -1. For now i use this loop:

int i;
int myArray[10];

for(i = 0; i < 10; i++)
    myArray[i] = -1;

There are faster ways?

0

4 Answers 4

9

The quickest way I know for the value -1 (or 0) is memset:

int v[10];
memset(v, -1, 10 * sizeof(int));

Anyway you can optimize the loop in this way:

int i;
for(i = 10; i--;)
    v[i] = -1;
Sign up to request clarification or add additional context in comments.

1 Comment

On two's complement machines. Won't work on exotic stuff like sign-and-magnitude. But since all the world nowadays is two's complement, yes.
6

If you want to initialize the array at the time of declaration with 0, you can use: int a[10] = {0}; which is very fast. But if you want to initialize with some other value or want to re-initialize your array with 0 at some point later in the code, use: memset(a, -1, size_a); (or memset(a, 0, size_a); respectively) or a loop. In my opinion, always prefer memset() to looping because memset() is often optimized to set entire words in memory to the initialization value given as its argument instead of setting individual bytes.

For stats, on my 32-bit Linux installation with 4GB memory and 2.2GHz*2 processor, the running times of four types of array initialization codes are given below:

1). 0.002s

#include <string.h>

#define SIZE 1000000

int a[SIZE];

int main(void)
{
    return 0;
}

2). 0.008s

#include <string.h>

#define SIZE 1000000

int main(void)
{
    int a[SIZE] = {0};
    return 0;
}

3). 0.003s

#include <string.h>

#define SIZE 1000000

int main(void)
{
    int a[SIZE];
    memset(a, -1, SIZE);
    return 0;
}

4). 0.011s

#include <string.h>

#define SIZE 1000000

int main(void)
{
    int a[SIZE];
    int i;
    for(i = 0; i < SIZE; i++)
        a[i] = -1;
    return 0;
}

2 Comments

The simple allocation loop will be optimized into a call to memset by any sane optimizing compiler.
Yes, with -O2 or with -O3, gcc 4.5.2 does optimize the allocation loop to memset()-like assembly code.
2

memset is very fast.

int arr[10];
memset(arr, -1, sizeof(arr));

However, what you have there will likely be turned into a call to memset by an optimizing compiler anyway. Look at your assembly output to make sure, but it is highly unlikely that the loop will remain a loop when compiled.

Comments

2

In GNU C what you can do is:

int myArray[10] = {[0 ... 9] = -1};

Initializing a range of elements: http://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html

And as nobody mentioned it, in portable C:

int myArray[10] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1};

1 Comment

@Nick This is not C but a GNU extension to C (enabled by default with gcc).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.