How can “while (i == i) ;” be a non-infinite loop in a single threaded application?

前端 未结 12 1157
甜味超标
甜味超标 2020-12-04 09:41

I just got a question that I can\'t answer.

Suppose you have this loop definition in Java:

while (i == i) ;

What is the type of

12条回答
  •  余生分开走
    2020-12-04 10:28

    I would add

    float i = Float.NaN;
    

    as well as

    double i = Double.NaN;
    

    A common trick in these sort of questions it in the assumption you make that i is an int. Other common assumptions might be s is a String, x,y are a double, ch is a char, b is a byte etc. If you see a question like this you can bet that 'i' is not its expect type.

    A similar question is; This never loops, what is 'x'

    while(x == x && x != x + 0) { }
    

    Another question I quite like is; This loop is an infinite loop, what are the possible values of x. (: I count twelve of them :)

    while(x != 0 && x == -x) { }
    

提交回复
热议问题