+ 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.
7 Antworten
+ 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.
+ 8
@Nanda You can also declare your variables anywhere you want in C++.
+ 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
+ 2
Thanks all
It means a variable cant become constant after declaration...
definitely Its value can be use.
+ 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;
+ 1
yes
0
Hello