I am trying to initialize an int with a particular value once only and use it repeatedly.
void some_method(int par){
int ch=1;
if (ch==1){
int x = par;
}
int y = x + 2;
}
I know this code will definitely not work because x is only within the scope of the if statement. some_method() is called repeatedly in a while loop, so if I declare x outside the if statement then every time some_method() is called, default to zero. I just want x to remain constant. I thought about just making x a global variable, but I am sure there has got to be a better solution than that. Any suggestions will be helpful!
Thanks.
This can be done with
staticvariables:Note that you then need to “pay” for the check of
initializedon every call, but if the work done to compute the value ofxis expensive enough it might be worth it.