Can a for loop be written to create an infinite loop or is it only while loops that do that?

前端 未结 12 1605
时光取名叫无心
时光取名叫无心 2021-01-17 23:58

Can a for loop be written in Java to create an infinite loop or is it only while loops that cause that problem?

12条回答
  •  盖世英雄少女心
    2021-01-18 00:51

    Just for fun (and this too long for a comment): a lot of people will be very surprised to learn that for a lot of very practical purposes the following is nearly an infinite loop:

        for (long i = Long.MIN_VALUE; i < Long.MAX_VALUE; i++) {
            ...
        }
    

    If the thread executing this loops can do 4 billions cycles per second and can do the increment and the check in one cycle (quite beefy for a single thread) and if my maths ain't totally off, I think the above code needs about 150 years to execute : )

提交回复
热议问题