• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Liutauras Vilda
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Saloon Keepers:
  • Scott Selikoff
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
  • Frits Walraven
Bartenders:
  • Stephan van Hulst
  • Carey Brown

Variable declaration in a loop

 
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
I've got a syntax question: is the following code legal in Java:

I think it is ok because it compiles, but it looks odd (I come from a C background where this is illegal). Is it better to declare the variable x outside the loop first?
Thanks,
Martin


[This message has been edited by Cindy Glass (edited October 04, 2001).]
 
Martin Rennix
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Damn pre tags! Here it is again properly formatted!
<pre>
for (i=0; i<10; i++)
{
int x = someValue();
doStuff(x);
}
</pre>
Martin
 
Ranch Hand
Posts: 1514
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes, it's legal. If it compiles, it is...

Bosun
 
Ranch Hand
Posts: 149
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It is legal but it may be better to declare x outside of the loop and with each pass simply assign it a new value
int x = 0;
for (i=0; i<10; i++)
{
x = someValue();
doStuff(x);
}
 
"The Hood"
Posts: 8521
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You get two different effects depanding on where you declare the variable. If you declare it inside the block, then it is local to the block, and POOF! it is gone when that execution of the block completes.
If you want the value to survive the block and be visible outside the block, then you need to declare it outside.
 
Politics n. Poly "many" + ticks "blood sucking insects". Tiny ad:
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic