Hello first thing first forgives me if I have mistakes in my English, I am beginner in c++ and I need help with this problem please
//global variables
int RangeOfArray;
int arr[RangeOfArray-1]; // error: array bound is not an integer constant before ']' token
void functionOne(){} // I need to access the array here.
void functionTwo(){} // as well here.
int main (){
cout<<"Type the length number of the array : ";
cin >> RangeOfArray;`
}
As you can see I need the array (arr) everywhere in my program but I can't why? I don't know
In these declarations
//global variables
int RangeOfArray;
int arr[RangeOfArray-1]; // error: array bound is not an integer constant before ']' token
there is declared the global variable RangeOfArray
that is implicitly initialized by zero and then there is declared the variable length array arr
with the size -1
that is implicitly converted to the maximum value of the type size_t
due to the usual arithmetic conversions because in C++ an expression that specifies a size of an array in its declaration is converted to the type size_t
.
For starters variable length arrays is not a standard C++ feature. And moreover you may not declare a variable length array with static storage duration.
And secondly using the expression -1
as the size of an array does not make a sense.
If you need a global variable that simulates an array then use the standard container std::vector<int>
.
For example
#include <iostream>
#include <vector>
//global variables
std::vector<int> arr;
void functionOne(){ /* ... */ } // I need to access the array here.
void functionTwo(){ /* ... */ } // as well here.
int main()
{
size_t RangeOfArray;
std::cout<<"Type the length number of the array : ";
std::cin >> RangeOfArray;`
arr.resize( RangeOfArray );
//...
}
The vector provides member function size
that reports the current number of elements stored in the vector. So you need not to make the variable RangeOfArray
global.
Pay attention to that it is not a good idea to use global variables.
So you could declare the vector in main and pass it by reference to functions where it is required.