Back to the basics: should I initialize my variables?

Published Thu, Oct 2 2008 15:31

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?

Filed under:

Comments

# Joao Paulo Carreiro said on Monday, October 06, 2008 5:54 AM

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?

# luisabreu said on Monday, October 06, 2008 7:45 AM

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)

# Manoj Mehta said on Friday, June 12, 2009 2:01 AM

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: blogs.msdn.com/.../what-does-the-optimize-switch-do.aspx

Leave a Comment

(required) 
(required) 
(optional)
(required) 
If you can't read this number refresh your screen
Enter the numbers above:  

Search

This Blog

Tags

Community

Archives

Syndication

Email Notifications

News




  • View Luis Abreu's profile on LinkedIn


    Follow me at Twitter

    My books

    Silverlight 4.0: Curso Completo

    ASP.NET 4.0: Curso Completo

    Portuguese LINQ book cover

    Portuguese ASP.NET 3.5 book cover

    Portuguese ASP.NET AJAX book cover

    Portuguese ASP.NET AJAX book cover