Declare array with declared constant - c++

I'm trying to do something like this:
const int array_size = 5;
string stuff[array_size];
My compiler won't let me compile this, even though array_size is a constant. Is there a way to do this without dealing with dynamic arrays?
Edit: "error C2057: expected constant expression"

I have answered this question assuming you are either coding in C or C++. If you are using a different language, this answer doesn't apply. However, you should update your question with the language you are trying to use.
Consider the following program:
int main () {
const int size = 5;
int x[size];
return 0;
}
This will compile in both C++ and C.99, but not C.89. In C.99, variable length arrays were introduced, and so locally scoped arrays can take on a size specified by a variable. However, arrays at file scope in C.99 cannot take a variable size parameter, and in C.89, all array definitions have to have a non variable size.
If you are using C.89, or defining a file scope array in C.99, you can use an enum to name your constant value. The enum can then be used to size the array definition. This is not necessary for C++ however, which allows a const integer type initialized by a literal to be used to size an array declaration.
enum { size = 5 };
int x[size];
int main () { return 0; }

#define array_size 5
string stuff[array_size];

You can use e.g. a vector or the new keyword to allocate memory dynamically, because declared arrays can not have runtime sizes.

Only thing I can think of is that you defined another array_size variable in your code, which is not a compile time constant and hides the original array_size.

array_size is not treated as a compile time constant. Constness added just makes sure that programmer can not modify it. If tried to modify accidentally, compiler will bring to your attention.
Size of an array needs to be a compile constant. Seems like your compiler is not supporting Variable Length Array. You can #define the size of the array instead which is treated as a constant expression.

Related

Passing value of const int in function to initialize array

I understand that arrays need to have a const int to be initialized, so I have this in main. I want this in main because I want to be able to modify these numbers easily if necessary.
const int magicWordCount = 10;
compareWords(magicWordCount);
The declaration of this function is:
void compareWords(const int);
The definition:
void Words::compareWords(const int magicWordCount)
{
std::string magic[magicWordCount] = {};
convertToStringArray(magicBuffer, magicBufferLength);
}
When I do this, "magicWordCount" in the definition is underlined by intellisense telling me, expression must have a constant value. I'm confused on where the value is NOT constant. Thoughts?
Although magicWordCount is const, as far as the compiler knows, it is a run-time constant, not a compile-time constant. In other words, it can ensure that the value of magicWordCount is not going to be changed inside Words::compareWords.
That is not enough to declare an array with the specific size: the compiler (and intellisense) are asking for a compile-time constant; magicWordCount is not a compile-time constant.
You can avoid this problem by using std::vector instead of an array:
std::vector<std::string> magic(magicWordCount);
The above will work even without const.
You could put magicWordCount in your Word class header, above your definition of the class. It's still easily accessible there, and you won't have to pass it in as a function parameter anymore.
it is the problem about array
because array is store in local scope
which mean if it did not have a const size(define before compile) it could make buffer overflow attack
for example the const int magicWordCount = 1000
the size of string[] will absolutely cover the return point
so in this situation you might use pointer instead
string* str = (string*)malloc(sizeof(string*) * a);
for(int i = 0; i < a; i++){str[i] = "";}
and also for my opinion, never use array, and instead with pointer
because the array perform really bad performance and a strange logic on read/write

how to revise a const int value c++

I have a "expected constant expression" error.
This is my error part:
int row=counter/4;
int goals[row][4];---> this part has error for "row" variable
how to define "row" variable like a constant value? or how to solve this problem?
C++ does not allow arrays of variable size. In your example, row is not a constant, and as such, can not be used to specify array size.
To workaround this, you might either switch to C (which does allow such arrays) or use C++ constructs - such as std::vector.
Syntaxically correct change would be to rephrase row as
const size_t row = counter / 4;
But than you'd need counter const, which you would not be able to do if you are getting it from the user input.
you can use only compile time constants in array declaring.
constexpr could help you,
http://en.cppreference.com/w/cpp/language/constexpr
but not for all compilers, look for the answer here:
constexpr function as array size

Complex array initialization in c++

There is a problem when I want to define a complex array:
#include<complex.h>
int main(){
int matrix=1000;
std::complex<double> y[matrix];
}
The error is "Variable length array of non-POD element type 'std::complex'
Is there something wrong with the definition of array here?
This kind of array only works with a length that is a constant expression, i.e. the length must be known at compile time.
To get a array of variable length, use an std::vector<std::complex<double>> y (matrix);
You should use std::vector (or std::array in some cases) over C-style arrays anyway.
You can't statically allocate a C++ array with size being a regular variable, since the value of matrix is not known until the program is executed. Try dynamically allocating your array:
std::complex<double> y = new std::complex<double>[matrix]
When you are doing using it, call:
delete[] y
The size of arrays must be know at compile time. It must be a constant expression. The value of matrix is only known at runtime. You must make matrix a constant to work.
const int matrix=1000;
The other way around is to use a vector whose size is variable and is initialized at runtime.
int matrix=1000;
std::vector<std::complex<double>> y(matrix);
C++ doesn't allow variable length arrays, either do it dynamically or use a vector.
Your compiler thinks that you are declaring a variable-length array, since matrix is non-const. Just make it constant and things should work:
const int matrix = 1000;
std::complex<double> y[matrix];
The error stems from the fact that variable-length arrays are only allowed for "dumb" data types, e.g. int/char/void* and structs, but not classes like std::complex.

Expected constant in 2d array

double rainPerMonth(const int YEARS)
{
int monthYear[MONTHS][YEARS];
// ...
}
Visual Studio shows a squiggly line underneath the array declaration, saying that YEARS must be a constant when I'm creating the array. Is this an IDE issue because the variable has yet to be initialized, or am I writing this incorrectly?
MONTHS is already declared globally.
An array size must be a constant expression - that is, a value known at compile time. (Some compilers offer C-style variable-length arrays as a non-standard extension, but I don't think Visual C++ does. Even if it does, it's better not to rely on such extensions.)
A function argument isn't known at compile time, so can't be used as an array size. Your best option is here is probably
std::vector<std::array<int, MONTHS>> monthYear(YEARS);
In C++, an array must be sized at compile time. What you are attempting to do is declare one that is sized at runtime. In the function you've declared, YEARS is only constant within the scope of the function. You could call it rainPerMonth(someInt); where someInt is the result of some user input (which shows you that the result is not a compile-time constant).
Variable Length Arrays are an extension to C, but not C++. To do what you want, you can use dynamic memory, or a std::vector.
I think your problem lies in the fact that C++ wants a constant in the sense of compile-time constant to create your variable monthYear. If you pass it as a function, it need not be known at compile time? For example:
const int x=2;
const int y=3;
char xyChoice;
std::cin >> xyChoice;
if (xyChoice == 'x')
rainPerMonth(x);
else
rainPerMonth(y);
I'm unsure, but it seems to me like this would give you a constant int being passed to your function, but the compiler wouldn't know what size to create an array for before runtime?

usage of const in c++

I am new to C++.I was going through a C++ book and it says
const int i[] = { 1, 2, 3, 4 };
float f[i[3]]; // Illegal
It says the declaration of the float variable is invalid during compilation.Why is that?
Suppose if we use
int i = 3;
float f[i];
It works.
What is the problem with the first situation?
Thanks.
So the first is illegal because an array must have a compile-time known bound, and i[3], while strictly speaking known at compile time, does not fulfill the criteria the language sets for "compile-time known".
The second is also illegal for the same reason.
Both cases, however, will generally be accepted by GCC because it supports C99-style runtime-sized arrays as an extension in C++. Pass the -pedantic flag to GCC to make it complain.
Edit: The C++ standard term is "integral constant expression", and things qualifying as such are described in detail in section 5.19 of the standard. The exact rules are non-trivial and C++11 has a much wider range of things that qualify due to constexpr, but in C++98, the list of legal things is, roughly:
integer literals
simple expressions involving only constants
non-type template parameters of integral type
variables of integral type declared as const and initialized with a constant expression
Your second example doesn't work and it shouldn't work.
i must be constant. This works
const int i = 3;
float f[i];
Just to expound on Sebastian's answer:
When you create a static array, the compiler must know how much space it needs to reserve. That means the array size must be known at compile-time. In other words, it must be a literal or a constant:
const int SIZE = 3;
int arr[SIZE]; // ok
int arr[3]; // also ok
int size = 3;
int arr[size]; // Not OK
Since the value of size could be different by the time the array is created, the oompiler won't know how much space to reserve for the array. If you declare it as const, it knows the value will not change, and can reserve the proper amount of space.
If you need an array of a variable size, you will need to create it dynamically using new (and make sure to clean it up with delete when you are done with it).
For arrays with lengths known only at runtime in C++ we have std::vector<T>. For builtin arrays the size must be known at compile-time. This is also true for C++11, although the much older C99-standard already supports dynamic stack arrays. See also the accepted answer of Why doesn't C++ support dynamic arrays on the stack?