> A variable is like a cup. Declaring a cup allocates a space for an int or string etc.
> Why I need to fill the cup with something before want to fill this cup??
> Why can't I just leave it empty until it is needed to store a variable
> received from user input, should that user input be required at some stage.
Defining a variable always implies initializing it - if you don't initialize it explicitly, it is default initialized. For some types (like int), default initialization is trivial initialization - nothing needs to be done. For others (like std::string), default initialization is not trivial - the default constructor comes into play. For example, for a std::string, the default constructor initializes it to an empty string.
The problem with code of this kind:
1 2 3 4 5 6 7 8
|
int number ; // initialization is trivial; number may contain any value at all
// ....
// sometime much later
std::cout << "please enter a number: " ;
std::cin >> number ; // assign a meaningful value (entered by the user) to number
// use number
|
is that it is prone to errors - because of a slip,
number may be used without having been assigned a meaningful value. For instance, in the above example, if when prompted with "please enter a number: ", the user enters
xyz, the attempted input fails, and nothing will get assigned to
number.
Also, where possible, postpone definition of a variable till the time time you know how to initialize it. If the initialization is trivial, it increases the clarity of code. If the initialization is not trivial, it could also make the code more efficient.
See:
http://www.civilnet.cn/book/kernel/Effective%20C++%20(Third%20Edition)/ch05lev1sec1.html