Thread: UNDECLARING a variable

  1. #1
    Unregistered Leeman_s's Avatar
    Join Date
    Oct 2001
    Posts
    753

    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.

  2. #2
    Ethereal Raccoon Procyon's Avatar
    Join Date
    Aug 2001
    Posts
    189
    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).

  3. #3
    Registered User
    Join Date
    Aug 2001
    Posts
    79
    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);
    All generalizations are false

  4. #4
    Registered User
    Join Date
    Sep 2001
    Posts
    412
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How accurate is the following...
    By emeyer in forum C Programming
    Replies: 22
    Last Post: 12-07-2005, 12:07 PM
  2. static class variable vs. global variable
    By nadamson6 in forum C++ Programming
    Replies: 18
    Last Post: 09-30-2005, 03:31 PM
  3. Replies: 2
    Last Post: 04-12-2004, 01:37 AM
  4. write Variable and open Variable and get Information
    By cyberbjorn in forum C++ Programming
    Replies: 2
    Last Post: 04-09-2004, 01:30 AM
  5. Variable question I can't find answer to
    By joelmon in forum C++ Programming
    Replies: 3
    Last Post: 02-12-2002, 04:11 AM