了解"for"循环的退出条件 [英] Understanding the exit condition of a 'for' loop
问题描述
阅读了堆栈溢出问题后,我有这个问题 使用C 以二进制表示形式打印int.
I had this question after reading the Stack Overflow quesion Print an int in binary representation using C.
在用户评论中,他们发布了此for
循环,该循环将1或0分配给位位置,以便从int十进制转换为char *二进制.
In a user's comment, they posted this for
loop, which assigns either a 1 or a 0 to the bit position in order to convert from an int decimal to char * binary.
for(; bits--; u >>= 1)
str[bits] = u & 1 ? '1' : '0';
我了解为什么不需要初始化值.这是我一直都知道的for
循环的语法:
I understand why there doesn't need to be an initialized value. This is the syntax for a for
loop that I've always known:
for ( variable initialization; condition; variable update )
我不明白"bit--"如何成为退出条件.请帮助我理解此代码的工作方式(我已经对其进行了测试,并且它是有效的).
I don't understand how 'bit--' can be an exit condition. Please help me understand how this code works (I tested it, and it is valid).
推荐答案
在C中,布尔值上下文中的零值计算为假".因此,当bits--
评估为0
时,在循环上下文中,其评估为"false"并终止循环.
In C, a value of zero evaluates to "false" in a boolean context. So when bits--
evaluates to 0
, in the context of the loop it evaluates to "false" and terminates the loop.
例如,如果您说:
int x = 1;
if (--x)
{
printf("True!\n");
}
else
{
printf("False!\n");
}
它将输出"False",因为--x
的计算结果为0,在布尔上下文中为"false".
It will output "False", because --x
evaluates to 0, which is "false" in a boolean context.
这篇关于了解"for"循环的退出条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!