Reset a Variable after a FOR loop

Is there a way to reset your variables to its original value after it breaks out of a FOR loop?
Yea, but you'll need to store it's original value in another variable. Or if it's known at compile time just manually reset it back to that in the code.

EDIT:
This is assuming the variable has scope outside of the loop. If not, that variable is gone forever once the loop exits.
Last edited on
I fail to understand what you mean. Your loop is a different scope. variables created in the loop, remain in the loop, ones that were created outside of it, used in the loop will keep the values they gained in the loop. unless you write some code to change them manually. So you could reset an int doing this; int x = 0;

Edit:

looking at ResidentBiscuit's answer, I think I misunderstood the OP's question.
Last edited on
If you don't want to modify a variable, then don't modify that variable.
you could modify a copy
Thank you guys. Essentially I have a variable that needs to reset when it is finished in the loop. It sounds like I'll need to create another variable to reset the original variable.


1
2
3
4
5
6
7
8
9
double easting;
double origEasting;

for(int j=0;j<=20;j++)	
	{
		outFile << easting << "\t" << northing << "\t" << beginElevation << "\t1" << "\t" << "Inj_Point-" << injPoint << endl;					
	}			
easting = origEasting;



Would this be correct?
Would this be correct?

Not exactly. Neither easting not origEasting is ever assigned any value before the loop. And neither is altered within the loop.
Line 8 simply assigns the random contents of origEasting to easting.

this might make more sense...
1
2
3
4
5
6
7
8
9
10
int count = 5;
int saveCount = count;

for (int j=0;j<=20;j++)
{
    count = count + j;
    cout << count << endl;
}

count = saveCount;

Last edited on
As Chervil says, you're not actually modifying anything, then assigning whatever garbage happens to lay in the memory of origEasting into easting.
Thanks guys, it really helps.
Topic archived. No new replies allowed.