@brock
To declare and initialize a global array in C++, you can follow these steps:
1
|
int globalArray[5]; |
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++.
@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.