Thread: Before initialising a variable

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

    Before initialising a variable

    Before I initialise a variable has it taken a value?

    For example I have got a code like that:

    Code:
    include <stdio.h>
    
    main()
    {
      const int a;
      printf("a=%d\n",a);
      return 0;
    }
    The output is that: a=2147348480

    What is that number? Is it random?

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    It is the contents of the memory location where a was stored. No new value was put there by you, consequently whatever was already there is still there.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    37,537
    No, it's garbage.

    And since integers are allowed to have trap representations, it might just crash your program.
    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.

  4. #4
    Registered User
    Join Date
    Dec 2010
    Posts
    113
    Quote Originally Posted by tabstop View Post
    It is the contents of the memory location where a was stored. No new value was put there by you, consequently whatever was already there is still there.
    Then I have to initialise a like that:

    Code:
    const int a=1;
    If I try to initialise it like this one;

    Code:
    const int a;
    a=1;
    That means:
    a=2147344384 at first
    then a=1

    Because const does not allow to modify, it give me an error.

    Am I right?

  5. #5
    The Dragon Reborn
    Join Date
    Nov 2009
    Location
    Dublin, Ireland
    Posts
    629
    yeah const wouldn't allow you to modify a variable. sort of like #define.
    It is always good to initialize your variables to 0 on declaration..what I learnt anyways.

    and a could have anything stored in it..not just 2147344384
    You ended that sentence with a preposition...Bastard!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Realloc problem, environment variables Linux C
    By yodakohl in forum C Programming
    Replies: 4
    Last Post: 01-05-2011, 07:04 PM
  2. Pointers
    By MrMatt027 in forum C++ Programming
    Replies: 14
    Last Post: 12-10-2010, 04:32 PM
  3. How accurate is the following...
    By emeyer in forum C Programming
    Replies: 22
    Last Post: 12-07-2005, 12:07 PM
  4. static class variable vs. global variable
    By nadamson6 in forum C++ Programming
    Replies: 18
    Last Post: 09-30-2005, 03:31 PM
  5. Replies: 2
    Last Post: 04-12-2004, 01:37 AM