Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I initialize an array globally in C or C++?

Tags:

c++

c

I'm trying to do this:

for(int k=0; k<context.size(); k++)
{
   cc_no_issue[k]=0;
}

Can someone tell me how I can do that globally? Whenever I try I get these errors:

expected unqualified-id before "for"
k does not define a type
k does not define a type

like image 311
cdub Avatar asked Aug 09 '11 04:08

cdub


People also ask

Can we initialize array globally?

The arrays can be declared and initialized globally as well as locally(i.e., in the particular scope of the program) in the program.

Can we declare array globally in C?

As in case of scalar variables, we can also use external or global arrays in a program, i. e., the arrays which are defined outside any function. These arrays have global scope. Thus, they can be used anywhere in the program.


Video Answer


2 Answers

This will do:

long cc_no_issue[100]={0};

And this is the proper initialization.

Note: this will initialize all the contents to 0.

This sentence:

long cc_no_issue[100]={1,2};

will set cc_no_issue[0] to 1, cc_no_issue[1] to 2, and the rest to 0. You could see the link above for more information.

like image 177
zw324 Avatar answered Oct 03 '22 23:10

zw324


If you have a global array of a basic type,

int some_array[1000];

It will automatically be initialized to zero. You do not have to initialize it. If you do need to run initialization code, you can do a hack like the following (in C++):

struct my_array_initializer {
    my_array_initializer() {
        // Initialize the global array here
    }
};
my_array_initializer dummy_variable;

If you are on GCC (or Clang), you can execute code before main with the constructor attribute:

__attribute__((constructor))
void initialize_array()
{
    // Initialize the global array here
}
like image 25
Dietrich Epp Avatar answered Oct 03 '22 23:10

Dietrich Epp