[CSI] CIN to Const

Mikhail Nesterenko mikhail at cs.kent.edu
Mon Oct 10 00:17:52 EDT 2016


>     cout << "Enter number: ";
>     int number; cin >> number;
>     const int size = number;
>     int myArray[ size ] = { };   // Error identified
> 
> My question is, why can't the values of variables be used to define a
> constant? Once the constant is initialized its value cannot be changed, why
> does it matter if it was initialized with the value of a construct whose
> value may (or may not) have since changed? Do we need to explicitly use the
> value of the variable? How is that done and is it reasonable to do so?

Array size needs to be known at compile time. This requirement is due
the way arrays are allocated. An array is allocated on the call stack
in the function frame that it is declared in, once the function is
invoked. For proper allocation, the frame size, including array size,
needs to be known at compile time.

To do what you want to do, you need to use a dynamically allocated
array. This is studied in CSIB.

Thanks,
--
Mikhaikl


More information about the cs13001 mailing list