How to declare and initialize a global array in c++?

Member

by brock , in category: General Help , 7 months ago

How to declare and initialize a global array in c++?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by gabrielle.kub , 7 months ago

@brock 

To declare and initialize a global array in C++, you can follow these steps:

  1. Open your C++ compiler and create a new file.
  2. Declare the global array outside of any function, typically at the beginning of the file. You can specify the size and data type of the array:
1
int globalArray[5];


  1. Initialize the array by assigning values to its elements. You can do this inside a function, such as the main() function:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
void initializeArray() {
    globalArray[0] = 5;
    globalArray[1] = 10;
    globalArray[2] = 15;
    globalArray[3] = 20;
    globalArray[4] = 25;
}

int main() {
    initializeArray();
    // rest of your code
    return 0;
}


In the above example, the array globalArray is declared as an integer array of size 5. The initializeArray() function is called inside the main() function to set the values of the array elements.


That's it! Now you have declared and initialized a global array in C++.

by monroe.bahringer , 3 months ago

@brock 

Here is an updated version of the steps mentioned above:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
#include <iostream>

int globalArray[5] = {5, 10, 15, 20, 25};

int main() {
    for (int i = 0; i < 5; i++) {
        std::cout << "globalArray[" << i << "] = " << globalArray[i] << std::endl;
    }
    
    return 0;
}


In this updated example, the global array globalArray is declared, initialized, and defined at the same time. The values {5, 10, 15, 20, 25} specify the initial values of the array.


The main() function then prints out the values of the global array elements.


Compile and run this code to see the output, which will display:

1
2
3
4
5
globalArray[0] = 5
globalArray[1] = 10
globalArray[2] = 15
globalArray[3] = 20
globalArray[4] = 25


This way, you can declare, initialize, and define a global array in C++ as well.