This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Variable initialization

 
Gregory Thomas
Greenhorn
Posts: 11
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am confused about when to initialize a variable and when not to. For example, in my code snippet

This example the String variable ex needs to be initialize:

why?

Thanks in advance

Gregory

[ edited to preserve formatting using the [code] and [/code] UBB tags -ds ]
[ September 17, 2004: Message edited by: Dirk Schreckmann ]
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When posting code, please be sure to surround the code with the [code] and [/code] UBB Tags. This will help to preserve the formatting of the code, thus making it easier to read and understand.
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Gregory, in your first example, did you mean for the comment to read, "This example String variable ex does need to be initialize?" Notice that your comment says the variable does not need to be initialized, which is incorrect.

In general, a variable must always be initialized before you use it for something other than assigning a value to.

In your first example, the variable is not initialized, and then you tried to use it to do something in the if-statement. Do you understand how that's a problem?

On the issue of when to initialize a variable, I'd recommend not declaring a variable until you're ready to initialize and use it. So, initialize variables when they're declared.
 
Gregory Thomas
Greenhorn
Posts: 11
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
oh boy... I was so confused that I did not read my comment thoroughly. Yes you are right.

Thank you for replying to me. Why do you "recommend not declaring a variable until you're ready to initialize and use it"? I had the same thought but my manager was questioning why I did that in a loop. For example:



Is it because I am creating several string instances?

Thanks again.
Gregory
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic