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

Member

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

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

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by gabrielle.kub , 2 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++.