Initialization of variables... was( RE: Newbie C++ programmer again... )
Rob Wehrli
rwehrli@azpower.com
Fri, 18 Aug 2000 09:45:55 -0700
rwehrli@azpower.com
Date: Fri, 18 Aug 2000 09:45:03 -0700
Message-Id: <16450323100334@azpower.com>
> It does solve his original post from a few days ago. I didn't initialize
> tester because I'm not looking at it until it was in a known state. I
> understand about initializing stack variables, I had a bug in a program a
> a while back that drove me nuts for about 3 years until I finally worked
> out it was because of a stack variable that wasn't initialized *sigh*.
> That said, the real trick isn't just to initialize, but to make sure
> variables are in 'known' states when you use them.
>
> rna
Not to dwell endlessly on it, however, initialization places the variable in a known state.
int i; // declaration *no* initialization of storage
int i = 0; // declaration and initialization and assignment to "known" value.
i = 0; // initialization and/or assignment if already initialized
int i; // declaration
int i(); // declaration and "default" initialization/assignment
int i(0); // declaration and initialization and assignment to "known" value.
If you:
int var; // declaration only!
cin >> var; // used before being initialized...ack!
...is var in a "known" state?
What happens when you...
cout >> var >> endl;
Don't you rely on what cin is doing to var to init var? What if the implementation of cin changes. Will var's state stay the same? The answer is undefined. We should initialize var's state before using it so that if the implementation of anything that uses var changes, var's state will be defined through our application. Just about everywhere you'll find transgressions of this "basic rule". I didn't come up with the rule. I simply tend to live by it because I know that if I initialize every single thing before I use it, I'll not have to worry someday that that is a problem I'll have to chase. Call it a preemptive strike :) I'm far too dumb and old and simple minded to not follow good rules when told to do so by good books...even when they don't always do it themselves ;)
While it isn't as likely that cin's implementation will change very soon, a "grand programmer elite" may simply override cin, something not likely to happen in "straight C"...and hose your implementation. Remove all doubt from your applications by initialization of all variables before using them. It's a good rule to follow.
Take Care.
Rob!