-
UNDECLARING a variable
well, is there a way to undeclare a variable? like i want to do this:
do
{
int x;
cin>>x
num=num-1
sum=sum+x
(now here is where i want to undeclare x);
}while(num>0);
see, i want to be able to have the user input x, store it in sum, and then be able to go back and input another value of x which will be added to sum.
-
Your code can already do that. You can replace the value in a variable as many times as you want, and (if you're using C++) even reinitialize it (or it least it looks like it).
-
put "int x; cin>>x; sum+=x;" into a function like this:
Code:
int addtosum(int sum)
{
int x = 0;
cin >> x;
sum+=x;
return sum;
}
do
{
sum = addtosum(sum);
num--;
} while (num>0);
This way, when the function ends, the int x variable goes out of scope and is forgotten.
A simpler way might be to simply move the int x; declaration outside of the do loop.
Code:
int x;
do{
cin >> x;
num--;
sum+=x;
}while (num>0);
-
Actually, in ANSI C++, your original code will work, because your variable only has scope within the braces of the do..while loop. So, it WILL automatically undeclare the variable.
Not all compilers support all scope rules, though, so you may just want to declare x outside of the loop, not inside.