I wonder why this two following codes give different results;
for(i = 1, j = 0; i < 10; i++) {
j += i;
System.out.println(i);
}
This one gives the numbers between 1 included and 10 excluded.
for(i = 1, j = 0; i < 10; i++)
j += i;
System.out.println(i);
However this one gives 10. I could not get the logic of this;
for()
do_something;
do_something_else;
That is because the default scope of an iteration in your case is the only line following it, something equivalent to -
for(i=1, j=0;i<10;i++) {
j += i;
}
System.out.println(i);
Hence the entire loop is iterated and since after that the value of i==10, that is your output in the second case.
In the first case, it's pretty obvious that the value is printed with each iteration and hence 1 to 9(less than 10) :
for(i=1, j=0;i<10;i++){
j += i;
System.out.println(i);
}
The for
loop, the while
loop, and the if
statement (ignoring else
) all control a single Statement:
for (
[ForInit];
[Expression];
[ForUpdate])
Statement
for (
{VariableModifier} UnannType VariableDeclaratorId:
Expression)
Statement
while (
Expression)
Statement
if (
Expression)
Statement
That statement may be a Block, i.e. braces {}
with multiple statements.
So, this code is all the same:
for(i=1, j=0;i<10;i++)
j += i;
System.out.println(i);
for(i=1, j=0;i<10;i++)
j += i;
System.out.println(i);
for(i=1, j=0;i<10;i++)
j += i;
System.out.println(i);
for(i=1, j=0;i<10;i++) {
j += i;
}
System.out.println(i);
The first two are very bad, because they hide (misrepresent) the code structure.
Many people advocate always using blocks, to prevent confusing and coding errors.
In the second example, the output is outside the for loop. A for loop without curly brackets only includes the following statement.
Loop without braces apply only to the next statement
So :
for(i=1, j=0;i<10;i++)
j += i;
System.out.println(i);
is equivalent to :
for(i=1, j=0;i<10;i++){
j += i;
}
System.out.println(i);
i
is defined out of loop scope and is incremented after the last loop so it has value of 10
The first statement contains a block of code. A block of code is handled as one unit.
To create a block of code you should insert statements between curly braces.
loop and conditional expressions are handling only the first statement under them, if no block of code specified.
Therefore:
// Both statements handled 10 times
for(i = 1, j = 0; i < 10; i++) {
j += i;
System.out.println(i);
}
// Only the first statement handled 10 times, the second one is out of scope of the loop
for(i = 1, j = 0; i < 10; i++)
j += i;
System.out.println(i);
来源:https://stackoverflow.com/questions/44221915/for-loop-without-braces-in-java