+ 4

Constant Variables

is there is any way to make a variable constant after declaration while we are using a variable in program and we want to make it a constant when we meet a specific value.

14th Jun 2017, 6:38 AM
Azam
Azam - avatar
7 odpowiedzi
+ 10
I get what you are trying to ask. I don't think there is a way to convert a variable to const/final var. However, this is what you can do: int z = 0; z++; ++z; //more codes const int N = z; When you cannot convert an existing variable to constant, the next best thing would prolly be to assign the value of the existing variable to a a new constant variable. The thing about constants is that they have to be initialised at declaration though.
14th Jun 2017, 6:59 AM
Hatsy Rei
Hatsy Rei - avatar
+ 8
@Nanda You can also declare your variables anywhere you want in C++.
14th Jun 2017, 7:03 AM
Hatsy Rei
Hatsy Rei - avatar
+ 5
You can also create a const pointer to the variable, and use const_cast to convert it to const. Here's an example. https://code.sololearn.com/cELf5b5RSuD7/?ref=app
14th Jun 2017, 8:05 AM
Karl T.
Karl T. - avatar
+ 2
Thanks all It means a variable cant become constant after declaration... definitely Its value can be use.
14th Jun 2017, 3:31 PM
Azam
Azam - avatar
+ 1
hi, In C++ u have to define or declare your variable at the beginning but in java u can declare any where. if you want to make the variable const after declaration then create another var and make that var as const with the value u want. ex: int a; after some processing a becomes 10 then create another var final int b=a;
14th Jun 2017, 7:00 AM
Nanda Balakrishnan
+ 1
yes
14th Jun 2017, 3:06 PM
Nanda Balakrishnan
0
Hello
14th Jun 2017, 3:02 PM
Michael
Michael - avatar