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

Why don't Java, C, and C ++ (possibly other languages ​​as well) allow more than one type to be used for for-loop variables? For example:

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

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

But I might want to have another variable whose scale is limited by a loop, and not every iteration. For example:

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

I store the obj.operation()returned data in variablebecause I want to use it only inside the loop. I do not want to be variablestored in memory and not remain visible after the execution of the loop. Not only for free memory space, but also to prevent unwanted behavior caused by misuse variable.

Therefore, loop variables are useful but not supported to a large extent due to type limitation. Imagine that a method operation()returns a long value. If this happens, I cannot take advantage of loop variables without casting and data loss. The following code does not compile in Java:

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

Again, does anyone know why there is a restriction of this type?

+3
source share
6 answers

This limitation exists because your requirement is rather unusual and can be obtained using a very similar (and only slightly more detailed) design. Java supports anonymous blocks of code to limit the 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++) { ... }
  }
}
+20

:

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

, :

int i = 0, long variable = obj.operation();

. . . int. , , int , . long , , .

, for.

+3

, (expr; expr; expr), . .

+2

@jsight , , - . , Java . Java , , , , , . , :

  • , , , .
  • Java .
  • , Java.
  • , / , for .

(IMO, - C ++. , - , .)

+1

- " " , Java , , , .

0

for , , . , .

So you can do this:

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

But in this case, the variable will be defined as int.

0
source

Source: https://habr.com/ru/post/1716150/


All Articles