• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Initialization in with in for block

 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello All,

I have a very simple and a silly doubt . why can't we declare a new variable inside for loop. Like

for(int i=0;i<5;i++)
int j=10; //No enclosing braces {}

After some analysis, I thought

int j=10; => int j; j=10; //Two separate steps

and since there is no block defined the above one is interpreted as

for(int i=0;i<5;i++)
{ int j;}
j=10; // Using un declared variable

Is my understanding correct, if so why should compiler separate both declaration and initialization.
 
Ranch Hand
Posts: 694
Mac OS X Eclipse IDE Firefox Browser
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This isn't exactly an answer to the question that you asked, but I like the coding convention where you always use braces. This makes it easy. It's a "no-brainer" to always type braces for loops and such.

Kaydell
 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Declaration of j was in for block,once the for block is finished the variable j is destroyed ,its a local variable .......hence using j outside this block will give an compiler error
 
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Leavitt & Chandra!!

What's the answer?
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Yogvinder,

When ever compiler sees int j=10;
internally it breaks it into int j; j=10; thats why when there is no braces around int j=10; it got declared with in for loop and lost its scope outside the loop. Hence we get compiler error for accessing an uninitialized variable.
 
reply
    Bookmark Topic Watch Topic
  • New Topic