Thread: What does the value of a not valued variable represents?

  1. #1
    Registered User
    Join Date
    Dec 2010
    Posts
    61

    What does the value of a not valued variable represents?

    Greetings EveryOne

    What does the value of a not valued variable represents?

    Isn't it a null variable, shouldn't a null variable be equal to 0?

    Code:
    #include <stdio.h>
    
    int main()
    {
        int x;
    
        printf("x = %d\n", x);
        
        return 0;
    }
    Thanks In Advance

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    If you have an uninitialised variable, then all bets are off as to what you get.
    - it might be zero (consistently)
    - it might be non-zero (consistently)
    - it might be random (over a small set of values)
    - it might be truly random (or seem so)
    - it might just crash your program.

    Doing absolutely anything (adding more code, changing your compiler, changing your compiler flags) can make anything else happen.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Dec 2007
    Posts
    2,675

  4. #4
    Registered User
    Join Date
    Dec 2010
    Posts
    61
    According to C FAQ :

    Variables with automatic duration (i.e. local variables without the static storage class) start out containing garbage, unless they are explicitly initialized. (Nothing useful can be predicted about the garbage.)
    what do you advice me to do, especially when declaring arrays as they might be long or moderately long?

  5. #5
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by Laythe View Post
    what do you advice me to do, especially when declaring arrays as they might be long or moderately long?
    Initialize them correctly....
    Code:
    int main (void)
      {
         int x = 0;   // single variable
         int y = 42; 
    
         int a[10] = {0};  // array
         int b[43] = {-1};
    
         // etc.
        return 0; 
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Pointers
    By MrMatt027 in forum C++ Programming
    Replies: 14
    Last Post: 12-10-2010, 04:32 PM
  2. Question about printing a variable???
    By Hoser83 in forum C++ Programming
    Replies: 2
    Last Post: 03-31-2006, 01:57 PM
  3. How accurate is the following...
    By emeyer in forum C Programming
    Replies: 22
    Last Post: 12-07-2005, 12:07 PM
  4. Use of variable
    By alice in forum C Programming
    Replies: 8
    Last Post: 06-05-2004, 07:32 AM
  5. Replies: 2
    Last Post: 04-12-2004, 01:37 AM