Populating Global Arrays

Problem: Declare a Global Array then, Populate each element individually.

ex. int LedNumber[120];
LedNumber[1] = 3;

When these two lines are placed outside of any function the compile fails with:

"expected constructor, destructor, or type conversion before '=' token "

The compile is successful when these two lines are placed withing a function.

What is going on?

try

int ledNumber[120] = { 10, 12, 14, 18, .. } ; // 120 numbers

Yes. Instructions mus be placed in functions. Only variable declaration (and a few other things) can be placed outside functions. So, this:

int LedNumber[120];

is not an instruction, so it can be placed outside a function, but this:

LedNumber[1] = 3;

is a instruction it can be placed inside a function.

The suggestion of robtillaart is the best way to initialize the array when you create the variable:

int ledNumber[120] = { 10, 12, 14, 18, ..    } ;  // 120 numbers

luisilva illustrates the differences quite nicely. However, the statement:

int LedNumber[120];

is a definition, not a declaration. Definition form an attribute list for the data item (e.g., an int array name LedNumber with 120 element) and allocates memory for it. A definition may appear outside of a function, in which case it has global scope.

A data declaration, on the other hand, also creates an attribute list, but does not allocate memory for it. For example:

extern int myGlobal;

Function prototypes are another common example of a data declaration. Data declarations may also appear outside a function.

Assignments, like:

LedNumber[1] = 3;

must appear within a function defintion and may have function or block scope.

Finally, a statement like:

int ledNumber[120] = { 10, 12, 14, 18, ..    } ;  // 120 numbers

is not an assignment even though is uses the assignment operator. Rather the statement is an itinitalization list. You can initialize non-aggregate data types as part of the definition.

Yes, you're right. I'm sorry for my bad English. :cold_sweat:

@luisilva: Your English is fine. The problem is that the vast majority of programmers fail to see the distinction between define and declare. While it may seem to be a trivial difference, there is a significant difference between the two terms. Understanding the distinction makes teaching some topics much easier if the student already knows the difference (e.g., explaining what extern means, the purpose of function prototypes, or object instantiation).