Type limitation in loop variables in Java, C and C++

fjsj picture fjsj · Aug 26, 2009 · Viewed 7.6k times · Source

Why Java, C and C++ (maybe other languages also) do not allow more than one type on for-loop variables? For example:

for (int i = 0; i < 15; i++)

in this case we have a loop variable i, which is the loop counter.

But I may want to have another variable which scope is limited to the loop, not to each iteration. For example:

for (int i = 0, variable = obj.operation(); i < 15; i++) { ... }

I'm storing obj.operation() return data in variable because I want to use it only inside the loop. I don't want variable to be kept in memory, nor stay visible after the loop execution. Not only to free memory space, but also to avoid undesired behaviour caused by the wrong use of variable.

Therefore, loop variables are useful, but aren't extensively supported because of its type limitation. Imagine that operation() method returns a long value. If this happens, I can't enjoy the advantages of loop variables without casting and losing data. The following code does not compile in Java:

for (int i = 0, long variable = obj.operation(); i < 15; i++) { ... }

Again, anybody know why this type limitation exists?

Answer

jsight picture jsight · Aug 26, 2009

This limitation exists because your requirement is fairly unusual, and can be gained with a very similar (and only slightly more verbose) construct. Java supports anonymous code blocks to restrict scope if you really want to do this:

public void method(int a) {
  int outerVar = 4;
  {
    long variable = obj.operation();
    for (int i = 0; i < 15; i++) { ... }
  }
}