how to revise a const int value c++ - 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

Related

declaration of a Multidimensional array without index numbers

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)

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?

constant function parameter as a static array size?

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".

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?

Declare array with declared constant

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.