Cheshire Cat Cheshire Cat - 1 year ago 71
C++ Question

Declare a table, then fill a table

Suppose we have a program, where we have big table. We want for first to get only a declaration, proceed, then after main loop fill whole table (for visual reasons). Something like that:

int MyBigTable[1000]


just like we can do with functions - first we get simple declaration, then we have main loop, after this we describe to compilator what do we want to do inside these functions. Sadly, tables are not this simple - when I try to make a pointer first, then construct with new[] operator whole array, I can't fill array with numbers. Any solution?

Answer Source

You can declare a global variable without defining it by using the extern keyword:

//declaration only
extern int MyBigTable[1000];

// ... functions which use MyBigTable ...

int MyBigTable[1000] = {1,2,3};

This also allows you to put the variable definition in a different source file. In this case, you'd normally put the extern declaration in a header file.