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
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:
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
In this case the preprocessor would leave the code like this:
That it is a valid instruction within the C ++ standard.
With constants the example should look like this:
const int constante 10;
// ^^^ tipo!!!
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:
std::cout << "Numero de elementos: ";
std::cin >> numElementos;
// Opcional: preparamos el contenedor para almacenar el numero de elementos
// dado por el usuario
while( numElementos-- )
std::cin >> valor;
for( size_t i = 0; i < elementos.size(); i++ )
std::cout << elementos[i] << '\n';