• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Naming variables in for loops

 
J Steele
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • 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?

 
Matthew Brown
Bartender
Posts: 4566
8
  • Mark post as helpful
  • send pies
  • 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
  • Quote
  • Report post to moderator
Thanks!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic