Constant initialing problem | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Constant initialing problem

const int Value = 541564; // Works without problem. But when I tried this... const int Value = Convert.ToInt32(Console.ReadLine()); I got this error : The expression being assigned to 'Value' must be constant. So it means Console.ReadLine() isn't a constant but 541564 is. Then I tried this one: int InitialValue1 = Convert.ToInt32(Console.ReadLine()); const int Value = InitialValue1; Again the same error. This also won't work: int InitialValue2 = 5343543; const int Value = InitialValue2; Any idea about why cannot assign a constant using user input. Is there a way to solve this?? I asked this question because I am curious to know why :) Thanks!!

6th Jul 2017, 1:38 PM
D3F4U1T
2 Answers
+ 2
Constants are something that you set and then it stays the exact same. What you're wanting is a variable, not a constant. Variables can be changed and can accept user input. For example: private const float pi = 3.141592; The value of pi never changes. It's always the same. As such, you can easily assign that value to a constant and then can use it as needed. If you're changing, convert, doing anything other than setting a constant value, then use a variable instead.
6th Jul 2017, 1:47 PM
AgentSmith
0
@Netkos Ent thanks for your clear answer. :)
6th Jul 2017, 2:30 PM
D3F4U1T