Back to the basics: should I initialize my variables?

If you’re an old C++ programmer, then you know that you must always initialize your variables (this has been recommended by Scott Meyers in his Effective C++ book). Now, I must say that I don’t really have an opinion on this one. Generally, I tend do initialize all my (local) variables, though I’ve read that doing this is bad for performance. Now, I don’t really know if this is the case or not. There are other reports on this, but I’m not sure that the penalty hit you’ll get is not worthy when you think about the legibility of the code (if you ask me, there has been enough compiler versions releases for getting that problem solved – I don’t know if that is the case or not). What I can garantee is that you’ll get a CS0165 error if you try to use a variable that hasn’t been initialized.

So, the question remains: should we initialize variables? what I do is initialize all local variables (ie, variables declared on methods) and leave class fields as they are. Opinions?


~ by Luis Abreu on October 2, 2008.

3 Responses to “Back to the basics: should I initialize my variables?”

  1. Don”t initialize, let the compiler warn you if you forgot to do so, as that means that the variable isn”t being used, right?

  2. unused variables are always signaled by resharper. I guess that some old habits die hard, and that”s why I still initialize local variables (and there are still some cases where they”re really must be initialized)

  3. I just read an article by Eric Lippert suggesting that when you switch on the “optimized” flag, all member variable initializers are optimized out.

    Here is the link to the post:

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: