Stephen Dedalus
Stephen Dedalus

Reputation: 133

C - How to define a global variable using a loop?

Sorry if this is a simple question, but I've searched this a lot and found nothing relevant, probably because I'm new to programming and don't know the specific jargons. So, I've a program that works fine. In the beginning of the code, I define the following array as a global variable:

static double arr[] = {
    [0] = 50,
    [1] = 0
};

However, I'm dealing with a huge amount of data my array need to have a lot of elements. If i was allowed to use a loop inside the definition of my variable, It would be very easy. However, everytime I try this i get the following error message

expected primary-expression before

What can I do in order to properly define the elements of my array?

Upvotes: 3

Views: 4571

Answers (2)

Ng Khin Hooi
Ng Khin Hooi

Reputation: 258

For C style array, you would need to declare the variable before hand with the necessary size.

static double arr[YOUR_SIZE];

Then only in main, you can populate the elements

int main () {
    for (int i=0; i < ((sizeof(arr))/(sizeof(arr[0])))); ++i) {
        //whatever here
        arr[i] = i;
    }
}

For C++, you could use runtime allocated vectors

std::vector<double> arr;

int main () {
    for (int i=0; i < YOUR_MAX; ++i) {
        arr[i] = i;
    }
}

Upvotes: 4

Jonathan Leffler
Jonathan Leffler

Reputation: 753890

Although you can use designated initializers in C99 and later, the standard requires the initializers to be written out long-hand. GCC provides a range-initialization extension so that you can initialize a range of indexes with the same non-zero value (you don't need the extension to initialize everything to zeros).

int array[100] =
{
    [50 ... 80] = 27,  // GCC extension
};

Note that the spaces are needed around the ellipsis because of the 'maximimal munch' rule. 50. looks like a valid floating point number, which is not, therefore a valid array index.

However, even in GCC, you can't have a loop written out in an initializer.

Upvotes: 1

Related Questions