3sm1r
3sm1r

Reputation: 530

initializing an array without using a for loop

If I want to create a vector of size components and I want all components to be 1, one way to do this is, of course, to use a for loop in this way

#include <stdio.h>

int main()
{
    int size=100;
    int array[size];
    for(int j=0; j<size; j++)
    {
        array[j]=1;
    }
}

But it doesn't look like the way programmers would do it. How can I do this vectorially, that is, without changing one element at a time?

Upvotes: 1

Views: 81

Answers (1)

David Ranieri
David Ranieri

Reputation: 41017

I'm afraid there are no alternatives to the loop in standard C.

If gcc is an option you can use Designated initializers to initialize a range of elements to the same value:

int array[] = {[0 ... 99] = 1};

Upvotes: 2

Related Questions