while(x) {
do_something();
}
will run do_something()
repeatedly as long as x
is true. In C, "true" means "not zero".
''
is a null character. Numerically, it's zero (the bits that represents ''
is the same as the number zero; just like a space is the number 0x20 = 32).
So you have while(*pointer != '')
. While the pointed-to -memory is not a zero byte. Earlier, I said "true" means "non-zero", so the comparison x != 0
(if x
is int
, short
, etc.) or x != ''
(if x
is char
) the same as just x
inside an if, while, etc.
Should you use this shorter form? In my opinion, no. It makes it less clear to someone reading the code what the intention is. If you write the comparison explicitly, it makes it a lot more obvious what the intention of the loop is, even if they technically mean the same thing to the compiler.
So if you write while(x)
, x
should be a boolean or a C int that represents a boolean (a true-or-false concept) already. If you write while(x != 0)
, then you care about x
being a nonzero integer and are doing something numerical with x
. If you write while(x != '')
, then x
is a char
and you want to keep going until you find a null character (you're probably processing a C string).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…