I have a trouble assigning a user input value to a constant variable. The code is below: | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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

13th Apr 2017, 4:28 PM
Baba Yunus Abdul Yekin
Baba Yunus Abdul Yekin - avatar
6 Answers
+ 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
13th Apr 2017, 5:06 PM
Shamima Yasmin
Shamima Yasmin - avatar
+ 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;
13th Apr 2017, 4:47 PM
Shamima Yasmin
Shamima Yasmin - avatar
+ 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.
13th Apr 2017, 6:07 PM
SoraKatadzuma
SoraKatadzuma - avatar
+ 8
thank you Shamima. Your idea has helped me solve the problem
14th Apr 2017, 11:13 PM
Baba Yunus Abdul Yekin
Baba Yunus Abdul Yekin - avatar
+ 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.
15th Apr 2017, 8:15 AM
Baba Yunus Abdul Yekin
Baba Yunus Abdul Yekin - avatar
+ 1
are u sure? I thought constant could not be modified at run time and must be initialized in design time.
13th Apr 2017, 4:50 PM
rodwynnejones
rodwynnejones - avatar