+ 10
I have a trouble assigning a user input value to a constant variable. The code is below:
int initial_value; const int c_value; cout<<"enter initial value"; cin>>initial_value; c_value = initial_value; My program still needs the initial user input value for making final calculation later in the code. Meanwhile the initial user input value is suppose to be changing as it goes through a loop in the code. So I declared a constant variable c_value and assigned the user input value to it after the user has made the input but it didn't work. Please help
6 ответов
+ 26
Good point @rodwynnejones. As long as I came to know, it depends on compiler, and this code is running well using my compiler.
For better solution (constexpr), you can see this reference:
http://stackoverflow.com/questions/27729080/c-const-variables-calculated-during-run-time
+ 24
Constant variables need an initial value. Just change the order of declaration.
int initial_value;
cout<<"enter initial value";
cin>>initial_value;
const int c_value = initial_value;
+ 10
If you want to create a constant variable but not a constant value, you can trying using a pointer like so:
int* const iptr = initial_value;
then you would later dereference the pointer. The pointer its self is constant but the value can be changed. Give it a try.
+ 8
thank you Shamima. Your idea has helped me solve the problem
+ 7
I didn't make c_value a constant anymore and it works. I declared c_value as a normal integer variable and assign it to intial_value after the cin<< and it works. It means as long as I don't modify c_value somewhere along the code, it value still remains the user input value.
+ 1
are u sure? I thought constant could not be modified at run time and must be initialized in design time.