I have a program I need to implement that has the following code:
for (int n = 1024; true; n+=n)
I cannot find any other examples of java loops having such a format. What does this mean? I've tried to research it, but I don't even know what to search for - it's totally foreign to me.
The basic for statement is described in the language spec :
for ( [ForInit] ; [Expression] ; [ForUpdate] ) Statement
You are asking about the case when Expression
is true
. (The square brackets above mean it is optional).
The meaning of that is described just below, in Sec 14.14.1.2 :
- If the Expression is not present, or it is present and the value resulting from its evaluation (including any possible unboxing) is true, then the contained Statement is executed.
...
- If the Expression is present and the value resulting from its evaluation (including any possible unboxing) is false, no further action is taken and the forstatement completes normally.
So, Expression
is present, and evaluates to true
(because true
evaluates to true
). Hence, Statement
is executed, and will continue to be executed because Expression
remains true
.
As such, it is an infinite loop (unless there is a break, return, throw or System.exit
inside the loop).
Why you dont use another loop? Use for example do-while instead of
for (int n = 1024; true; n+=n)
You can make a work around with:
int n=1024;
do{
//your code
n+=n;
}while(condition==false);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.