RAM Allocation for an int Variable

Greetings,

Have finally acted upon my fascination with computer programming and am exploring C++.

Am playing with variables and how their values are displayed. Thought I'd see what happens when I attempt to input a character into an int testNumber variable. I did the same with a string. What I got is curious to me. In all attempts I got the same number, 8642825.

I'm thinking that this number results from the active bits in the RAM address for this specific variable. And what is happening is that attempting to put a value other than an integer datatype results in NO value being put in. Is this true?

Thanks for a giving some attention to an enthusiastic newbie. :)

Hello Jim McLean,

Welcome to the forum.

The chances are that you did not initialize your variables when they were defined. The value at the memory location for the "int" that was defined is whatever happens to be there. In your case that value comes out to be "8642825". Usually in my case this number tends to be "-858993460". Basically this is referred to as garbage.

Not seeing your code I am guessing you did something like this:

1
2
3
4
5
6
7
8
9
10
int main()
{
    int num;

    std::cin >> num;

    std::cout << num << std::endl;

    return 0;
}


In the case of line 5 this is formatted input. Therefor "cin" expects a number to put in "num". If you would enter a letter it would look like it was excepted, but actually "cin" has been put in a failed state and nothing was put int "num" so it still contains the garbage from when it was defined.

It is always best and good programming to initialize your variables when they are defined. From C++11 on you can use an empty set of {}s. This will initialize "int"s to 0 and doubles to 0.0 and "char"s to '\0'. An exception is "std::string" this is empty when defined and does not need initialized. Should you need a variable to be initialized to a given value just put it between the {}s.

Your assessment of the problem although not quite the way to explain it is in the right direction.

Hope that helps,

Andy
Much appreciated, Andy.

You are correct in that I didn't initialize the variable. And your answer makes sense.
Hello Jim McLean,

You are welcome. Any time.

Andy
Topic archived. No new replies allowed.