This week's book giveaway is in the Cloud forum.
We're giving away four copies of The Business Blockchain and have William Mougayar on-line!
See this thread for details.
Win a copy of The Business Blockchain this week in the Cloud forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

A bit of confusion about "variable declared (not just initialized)", p. 362 (K&B7)

 
Mark Kevin
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

I find this line in the third bullet of the two-minute drill on page 362 confusing:

"A variable declared (not just initialized) within the basic for loop ..."

At first I thought it was a typo and the writer meant "A variable initialized, not just declared ... " because a variable must be declared before it is initialized, but then I realized they probably meant the following:

"A declared variable, or a declared variable that is also initialized ... "

or maybe, "A declared variable, whether or not initialized ..."

Not sure if I was the only one thrown off.
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mark Kevin wrote:At first I thought it was a typo and the writer meant "A variable initialized, not just declared ... " because a variable must be declared before it is initialized, but then I realized they probably meant the following:

"A declared variable, or a declared variable that is also initialized ... "

or maybe, "A declared variable, whether or not initialized ..."

Not sure if I was the only one thrown off.

That statement is about nothing more than the scope of a variable which is declared in a basic for loop. So if you declare a variable in the basic for loop, you can't use it outside this for loop as illustrated in this code snippetIf you want to use the variable inside the for loop, you must initialize this variable (as you already mentioned). But you can perfectly declare a few variables without assigning a value. This code snippet compiles and runs successfully

But you could have also declared a variable before the basic for loop and initialize it inside the basic for loop. Such a variable can still be used outside the basic for loop. That's what's the "(not just initialized)" part in that statement is all about. This code snippet will compile and run successfully

Hope it helps!
Kind regards,
Roel
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic