C++ – A few questions about initializing variables

cinitializationvariables

I'm in an introductory programming class and we're only in lesson two, so try to keep terminology simple, ha.

I'm a bit confused about when you need to and when you don't need to initialize a variable.

My book says initialization is when you assign a value to a variable after it's declared.

I later looked at my language champion pdf, and it only showed initialized values when we weren't prompting a user.

It showed that if we wanted to display our name, age, and dollars, all we'd put is initialized statements.

However, if we wanted to know information from the user concerning values, there wasn't any initialized statement: only declarative ones.

Tell me if I'm misinterpreting this.
http://prntscr.com/beu3hw
http://prntscr.com/beu3s7

If I'm correct, can someone explain what advantages there are to initializing values and why uninitialized variables commonly cause logic errors?

My book also says in many languages uninitialized values values hold unpredictable values; this is due to those languages setting aside a place in memory for the variable, but not altering the contents of that place in memory.

Could someone perhaps word this in a different way?

Best Answer

In languages like C, newly-declared variables essentially point to a (more or less) random memory location. If you declare the variable without also initializing it, it will contain whatever random value the memory happens to contain at the location in memory that the new variable points to.* Using the variable in this state will cause unpredictable behavior.

Assigning a value to the variable means that the memory location is set to the value that you have assigned, so that you and your program now have an expectation of what that variable contains.

*This description is deliberately simplified. Your actual mileage may vary.