• 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

Naming variables in for loops

 
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

I'm new here and I'm guessing this is a painfully basic question, but I can't find an answer.

I am writing a simple program with several classes, methods, and for loops. For the "counter" variable (not sure if this is the correct term) in the for loop ("int i" in the code below), do I need a new variable name for each for loop? In other words - in which of the examples below can I not (or should I not) use the name "i" for the int variable in the for loop?

 
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi. Welcome to the Ranch!

As long as you're declaring the loop counter in the loop expression (that's what the for(int i = 0;... bit does) then the scope of that variable is limited to the loop. So if loops don't overlap then you can use the same name. And if they are in different methods there's definitely no problem - variables declared within a method can't interfere with variables in other methods.

But when you've got nested loops you need different names. On your line 10 you should be able to refer to both counters, so you need to be able to tell them apart.

While you're at it - using i for a simple loop counter is usually fine. It's pretty standard usage. But once you start nesting loops it's easy to get the indexes mixed up, so I'd usually suggest trying to give them more meaningful names.
 
J Steele
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks!
reply
    Bookmark Topic Watch Topic
  • New Topic