So, I read a lot of professionally published books and articles with code examples that don't initialize their variables. Personally, I see no downside to always initializing each of your variables when you declare them - even if it's just to 0 or nullptr. Is there any compelling reason, besides laziness, to not always initialize your variables when you declare them? Like, for instance, is memory not allocated for a variable until it gets its first value, or something weird like that?
I dont think its laziness. When you become an expert at programming, you will know when you need to initialize, and when you do not need to. So the question becomes, Why would you initialize if you dont have to?
Actually am thinking this is a sign of bad programming practice , having uninitialized variables in your code is a sign of poor design surely , you should totally avoid this whenever possible, i guess a good way would be to declare a variable only when needed as compared to having it laying around for no reason using up some memory, uninitialized variables are also sources of hard to find bugs , imagine having a million lines of code and at the middle sits an uninit variable that feeds garbage to you program, locating such an error could use some mega.. amount of time you definitely don't want to end up in such a situation.
Advice : keep your code safe , avoid uninitialized variables whenever possible
declare variables only when needed, also you might wanna check out the RAII idiom http://www.hackcraft.net/raii/
If you know for sure that the variable created will always be setted before used, there is no point in using the extra processing to intitalize them. For example
1 2 3 4 5
int myNumber;
// Shit is going on
cout<<myNumber<<"\n";
In this case myNumber will be used without getting setted or initialized, which may cause problems so you should init myNumber in this case
However
1 2 3 4 5 6
int myNumber;
// Shit is going on
myNumber = setMyNumber(userInput);
cout<<myNumber<<"\n";
In this case myNumber is not used or included in calculations our outputs before it gets set. Which means the value of myNumber before setMyNumber(int); doesnt matter and brings no value to the code itself. However unless its a really big system och program, init variables makes it easier to read the code and should be implemented as much as you can. No need to save memory on a 60 row console program.
Right. OK. This makes sense. It seems like the answer is: It's preferential minutiae. Some say "Why?" some say "Why not?". I was thinking perhaps there was a compelling reason like optimization/performance or memory management.
Personally, I feel like -- when it comes to pointers especially -- being in the habit of initializing when you declare your variable is important, as calling delete on a nullptr can be handled fine, whereas calling delete on an uninitialized pointer resulted in undefined behavior.
Perhaps it's in my "defensive programming" nature.