Conceptual doubt:

when i just declare an integer or other variable, no memory is allocated to it. So, then if i do cout for that variable, what exactly happens?, is there any garbage memory stored in that identifier? (i think not, coz after running the program it would have given a garbage value.)

e.g. of the code:

char a;
cout << a;
or

char arr[5];
cout << arr;
when i just declare an integer or other variable, no memory is allocated to it.


Memory *is* allocated to it, but the program doesn't initialize it with any value unless you tell it to.

If you print it, you'll see random garbage. It's basically whatever the memory happened to be at that time.
Memory is allocated when you declare it. Perhaps some compiler optimizations would get rid of any unused variables, but they'll most likely give you just warnings. The reason you get "garbage values" is because you never assigned a value to that memory, so whatever was there when it was allocated is still there.
1
2
char arr[5];
cout << arr; 


This is different though. When you do that you are putting the memory location on the screen, not the value held in that location. It isn't junk at all.
Last edited on
LowestOne wrote:
When you do that you are putting the memory location on the screen, not the value held in that location. It isn't junk at all.
Not in this case since it is a c-string it will print the value which in this case should be garbage. Arrays of any other type would print the address of the first index.
Memory *is* allocated to it, but the program doesn't initialize it with any value unless you tell it to.


This1.

1 I beleive there are some cases where it would be initialized for you but it's best to not rely on that.
Topic archived. No new replies allowed.