a teacher told us in class that we can not tell an arrangement to measure a variable
Defining an array based on a size given by a variable is known as VLA (Variable Length Array) and, effectively, it is a feature that is not supported by the C ++ standard ... although many compilers know how to deal with it .
One of the reasons is that sizeof
, a function used to know how many bytes an element occupies, is evaluated at compile time. For this function to be used with arrays it is necessary that the size of these is defined at compile time.
But for example can I create a constant and tell it to measure a variable to put the constant in the array?
Exactly. The constants are evaluated at compile time, then the size of the array will be known at compile time. Satisfied requirement.
What I will allow myself is to make a point at this point. The example you propose:
#define constante x
int array[constante];
It is not declaring a constant but rather it is a directive of the precompiler and no, it is not the same:
- Constants have a strong typing, which allows the compiler to do their job better. The macros do not have any typing since it is determined after the replacement.
- Constants have a scope, while a macro replaces all matches (they are very invasive)
- Constants can not be redefined and can not be modified, while macros can be redefined as many times as desired, which can affect the substitution made.
Also, the defined macro #define constante x
is not defining a constant in itself, but after acting the preprocessor your code would look like this:
int array[x];
With what you would be defining a VLA ... which as we have seen is not something supported by the C ++ standard. Another thing is that your code was the following:
#define constante 10
int array[constante];
In this case the preprocessor would leave the code like this:
int array[10];
That it is a valid instruction within the C ++ standard.
With constants the example should look like this:
const int constante 10;
// ^^^ tipo!!!
int array[constante];
Or if not in what way I can tell the arrangement to measure what the user asks me to do.
What you should do in that case is to use the dynamic memory or the containers of the STL.
On how to manage dynamic memory I recommend you take a look at the response from @PaperBirdMaster .
Using containers from the STL has the advantage that it is not essential (although it is advisable) to know in advance the number of elements:
#include <vector>
#include <iostream>
int main()
{
int numElementos;
std::cout << "Numero de elementos: ";
std::cin >> numElementos;
std::vector<int> elementos;
// Opcional: preparamos el contenedor para almacenar el numero de elementos
// dado por el usuario
elementos.reserve(numElementos);
while( numElementos-- )
{
int valor;
std::cin >> valor;
elementos.push_back(valor);
}
for( size_t i = 0; i < elementos.size(); i++ )
std::cout << elementos[i] << '\n';
}