Thread: variable not intialized but still has value?

  1. #1

    Exclamation variable not intialized but still has value?

    When I was messing around I just made this program to see what would happen-


    Code:
    #include <iostream>
    
    int main()
    {
        int x;
        std::cout << x;
        return 0;
    }
    and I got some strange number. Why is this?

  2. #2
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    A variable will always hold a value, in your case it's just undefined which is why you see garbage.

    The data you are seeing is what was left in that memory chunk by whatever wrote there before.
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  3. #3
    if it hasn't been written to since you have turned on your computer does it equal 0?

  4. #4
    Registered User
    Join Date
    Nov 2002
    Posts
    1,109
    french, not necessarily (at least I don't think so).

  5. #5
    Programming Sex-God Polymorphic OOP's Avatar
    Join Date
    Nov 2002
    Posts
    1,078
    The only variables that are guaranteed to be initialized to 0 are variables and objects that are not on the stack or heap (unless another value is explicitly specified).

    For instance, globals are guaranteed to be initialized to 0.

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