Home > Back-end >  initializing an array without using a for loop
initializing an array without using a for loop

Time:12-14

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?

CodePudding user response:

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};
  • Related