Thread: Small question: Why do I get a Debug error (variable not initialized)?

  1. #1
    Registered User
    Join Date
    Sep 2018
    Posts
    217

    Small question: Why do I get a Debug error (variable not initialized)?

    Notice the following program:
    Code:
    #include <iostream>
    using namespace std;
    
    int main(){
    
        for (int i = 0; i < 5; i++) {
            bool variable;
            
            if (i == 0)
                variable = true;
    
            if (variable)
                cout << "variable is true\n";
            else
                cout << "variable is false\n";
        }
    
        cin.get();
        return 0;
    }
    (I'm using Microsoft Visual Studios to compile)

    Here, when I try to compile the program, I get a Debug error (attached below).
    Small question: Why do I get a Debug error (variable not initialized)?-error-png

    Now if I click on the "ignore" (which I would have to do 5 times, one for every time the compiler reaches the if statement), I get the desired output which is "variable is true", 5 times.

    So technically the program is working but why do I get this debug error? What's an alternative and or how do I stop this kind of response and does it have a purpose?

    Thanks for reading, Cheers!

  2. #2
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    You need to initialize the variable "variable" before you try to use it, which you're not doing in most iterations of the loop. Realize that this variable is a different instance every time you go through that loop and you only initialize the first instance.

    By the way if you hit "Retry" instead of "Ignore" you would go into the debugger and then you might be able to see the problem.

  3. #3
    Registered User
    Join Date
    Sep 2018
    Posts
    217
    Quote Originally Posted by jimblumberg View Post
    You need to initialize the variable "variable" before you try to use it, which you're not doing in most iterations of the loop. Realize that this variable is a different instance every time you go through that loop and you only initialize the first instance.

    By the way if you hit "Retry" instead of "Ignore" you would go into the debugger and then you might be able to see the problem.
    But variable is assigned true in the first iteration itself.. So it would be true for all iterations, which it was when I ignored the debug error. I even tried declaring variable as false outside the loop to test what you said.. but got the same output.

    Hitting retry just led to the if statement

  4. #4
    Registered User
    Join Date
    Dec 2017
    Posts
    1,631
    Quote Originally Posted by Nwb View Post
    But variable is assigned true in the first iteration itself
    But what about the later iterations? Since you've declared it inside the loop body, variable is not guaranteed to hold it's last assigned value between loop iterations. According to the standard it's basically a new variable every iteration, although most systems probably implement it in such a way that your program would "work". But it's still technically incorrect and it could possibly fail on some systems.


    If you want variable to retain it's last set value between loop iterations then you need to declare it (and preferably initialize it) before the loop.
    Code:
    #include <iostream>
    using namespace std;
      
    int main(){
        bool variable = true;
        for (int i = 0; i < 5; i++) {
            if (variable)
                cout << "variable is true\n";
            else
                cout << "variable is false\n";
            if (i >= 2)
                variable = false;
        }
        return 0;
    }
    Last edited by john.c; 10-04-2018 at 06:43 PM.
    A little inaccuracy saves tons of explanation. - H.H. Munro

  5. #5
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    To illustrate what john.c is saying, it might be helpful to initialise to false, then compile and run the program:
    Code:
    #include <iostream>
    using namespace std;
     
    int main(){
     
        for (int i = 0; i < 5; i++) {
            bool variable = false;
             
            if (i == 0)
                variable = true;
     
            if (variable)
                cout << "variable is true\n";
            else
                cout << "variable is false\n";
        }
     
        cin.get();
        return 0;
    }
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  6. #6
    Registered User
    Join Date
    Sep 2018
    Posts
    217
    Quote Originally Posted by john.c View Post
    But what about the later iterations? Since you've declared it inside the loop body, variable is not guaranteed to hold it's last assigned value between loop iterations. According to the standard it's basically a new variable every iteration, although most systems probably implement it in such a way that your program would "work". But it's still technically incorrect and it could possibly fail on some systems.


    If you want variable to retain it's last set value between loop iterations then you need to declare it (and preferably initialize it) before the loop.
    Code:
    #include <iostream>
    using namespace std;
      
    int main(){
        bool variable = true;
        for (int i = 0; i < 5; i++) {
            if (variable)
                cout << "variable is true\n";
            else
                cout << "variable is false\n";
            if (i >= 2)
                variable = false;
        }
        return 0;
    }
    Quote Originally Posted by laserlight View Post
    To illustrate what john.c is saying, it might be helpful to initialise to false, then compile and run the program:
    Code:
    #include <iostream>
    using namespace std;
     
    int main(){
     
        for (int i = 0; i < 5; i++) {
            bool variable = false;
             
            if (i == 0)
                variable = true;
     
            if (variable)
                cout << "variable is true\n";
            else
                cout << "variable is false\n";
        }
     
        cin.get();
        return 0;
    }

    OHHH so what is happening is that 'variable' is being re-declared on the second iteration because of the statement 'bool variable'? So that means it will delete the old variable and create a new variable whose value isn't initialized?

    Thanks a lot laserlight your example really helped! Thanks jimblumberg and john.c I really appreciate that you took your time to help me !

    Okay back to the program, I intended on declaring the variable inside the for-loop so it would be local to the loop. So the variable would be deleted after the for-loop.
    An alternative is declaring the variable outside the loop and forming a block which holds the declaration and the for-loop so that the variable is local to the block and gets deleted after the block ends (if I understand this correctly).

    But I was thinking about instead using 'delete variable;' so does this make sense?

    Any tips guys? The main reason I'm doing this is to save memory.

  7. #7
    Registered User
    Join Date
    Dec 2017
    Posts
    1,631
    You can't depend on block-local variables to save you any memory. Most likely they don't since it's a waste of time to allocate/deallocate them on the stack every iteration. Most implementations probably allocate all stack memory of all blocks at the start of the function and release it at the end. Some locations may be used for two or more variables in different inner blocks, but that's not something you have to worry about. The compiler's optimizer is better than you at figuring out how to do it.

    "delete" frees the "heap" (non-stack) memory that a pointer points to. The memory the pointer itself uses (to store the address of the pointed-to heap memory) is still on the stack. So it saves no memory for a bool or int or probably even a long. It's for larger structures/arrays/etc.

    Anyway, don't nit-pick to save memory until you've proven that your program is using too much. And in that case, you need to determine where you can save the most and optimize there.
    A little inaccuracy saves tons of explanation. - H.H. Munro

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. variable is being used without initialized
    By Aeoskype in forum C++ Programming
    Replies: 2
    Last Post: 01-27-2015, 01:10 PM
  2. Replies: 4
    Last Post: 05-06-2013, 11:23 PM
  3. error : variable-sized object 'largeArray2' may not be initialized
    By funnydarkvador in forum C++ Programming
    Replies: 9
    Last Post: 03-02-2013, 11:09 AM
  4. Replies: 4
    Last Post: 04-08-2011, 10:56 PM
  5. how do I know a variable is not initialized?
    By patiobarbecue in forum C++ Programming
    Replies: 7
    Last Post: 01-17-2009, 06:49 AM

Tags for this Thread