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?
Related
I was wondering how it is possible to declare char arrays this way:
char szArray[]={"one"};
char szArrayTwo[][6]={{"one"},{"two"},{"three"}};
But this way doesn't work
char szArrayTwo[][]={{"one"},{"two"},{"three"}};
NOTE:
I am aware of the c++ tag even though it should be c, but it is being used in the c++ context with a c++ compiler
In fact it could be done for constant expressions used as initializers. But in this case for example for character arrays the compiler has to calculate the maximum length of string literals. And it is more difficult if an array is multidimensional.
The task will be more complicated if initializers are calculated at run time. In fact it is impossible to generate an appropriate code by the compiler.
In c++, an array with 2 dimension or more, the rightmost dimensions must always be defined.
string ArrayOne[] { "one","two","three" };
will work, and so will
char* ArrayTwo[] { "one","two","three" };
but a true multidimensional array must have at most one undefined dimension size (the leftmost)
I am not completely sure why this isn't working
void foo(const int a=10){
const int b = 10;
int c[a];
int d[b];
}
I thought that I say to the compiler the a is constant - I even tell it that default value is 10 :).
Why is he yelling:
1>sum_floats_txt.cpp(105): error C2057: expected constant expression
1>sum_floats_txt.cpp(105): error C2466: cannot allocate an array of constant size 0
1>sum_floats_txt.cpp(105): error C2133: 'c' : unknown size
I know what it tells me, but I do not know how to do what I want to do:
- function with static array inside of size dependable on outside constant
The function is counting something and returning the time spended on the execution (doing it in RTOS).
So I want to call this function with different parameters from main. To find out for which parameter it executes the shortest.
Is the problem in the way the static arrays works? It must have a constant size in the time of compilation. So for different static arrays I must define more of them.
Possible solution is to create more functions or more static arrays with different sizes predefined. And call them one after the other, but there are thousands of different sizes.
I do not want to do the non-automatized iteration to get the best parameters! Could arguments from main passed to the function before execution help?
VS2010 + RTX64 2013 (should not be the problem)
win7
thanks!
Don't mix up const qualified and constant.
const qualified just says that you don't have the right to modify the variable.
In C++ if a const qualified variable is also a compile time constant, the construct that you are using would be allowed. Here it is a parameter to a function, so there is no way that the compiler may know a value that it would substitute at compile time.
In C, things are different. In modern C, that is C since 1999, variable length arrays with such values that are only known during execution are allowed. Unfortunately there are still C compilers that don't conform to C99. AFAIR micorsoft compilers are among these.
The const int a argument is "read only" argument. It is not necessarily a value that the compiler knows at compile time. You can use a template argument though.
template <int N = 42>
void foo() {
int myArray[N];
}
C however does allow what you wrote there, C++ doesn't but will in C++14 with "std::dynarray".
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?
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.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Is there a way to initialize an array with non-constant variables? (C++)
I have the following code:
vector<vector<vec2>> vinciP;
int myLines = -1;
myLines = drawPolyLineFile("vinci.dat", vinciP);
if (myLines > -1)
{
cout << "\n\nSUCCESS";
vec2 vPoints[myLines];
for (int i = 0; i < NumPoints; ++i)
{
vPoints[i] = vinciP[0][i];
}
}
I'm getting an error on the line 'vec2 vPoints[myLines];' that says expressions must have a constant value. I don't understand why I'm getting this error, any help?
Is it because myLines could be negative? idk.
vec2 vPoints[myLines];
Since myLines is not a const expression ((which means, it is not known at compile-time), so the above code declares a variable length array which is not allowed in C++. Only C99 has this feature. Your compiler might have this as an extension (but that is not Standard C++).
The solution to such commom problem is : use std::vector<T> as:
std::vector<vec2> vPoints(myLines);
It should work now.
Is it because myLines could be negative?
No, It is because myLines is not a compile time constant.
Explanation:
vec2 vPoints[myLines];
Creates an array of variable length, where myLines value will be determined at Run-time.
Variable length arrays are not allowed in C++. It was a feature introduced in C99, and C++ Standard does not support it. Some C++ compilers support it as an extension though but it is nevertheless non standard conforming.
For C++ size of an array should be known at compile time and hence must be compile time constant. myLines is not a compile time constant and hence the error.
You should use a std::vector
vec2 vPoints[myLines];
Array size must be a compile time constant. myLines is not a compile time constant. Instead, allocate the memory using new or even better to use std::vector.
C++ does not have variable-length arrays. The size of an array must be determined at compile-time. The value of myLines is only known at runtime, so this won't work.
To have arrays whose size is only known at runtime, use std::vector.
std::vector<vec2> vPoints(myLines);
You are getting that error because static arrays need a static (constant) size. Since the number of components in your vPoints is dynamic, consider using a dynamic array instead. Or better yet stick with vector.