了解for循环的退出条件 [英] Understanding the exit condition of a for loop

查看:163
本文介绍了了解for循环的退出条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个问题,阅读此线程<一后href=\"http://stackoverflow.com/questions/1024389/print-an-int-in-binary-re$p$psentation-using-c\">Print使用C 二进制重新presentation一个int

I had this question after reading this thread Print an int in binary representation using C

在一个用户发表评论,他们张贴了这个循环,它指定无论是1或者为了从int十进制转换为char 0的位位置*二进制文件。

In a users 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--可以退出条件。请帮助我了解这个code是如何工作(我测试了它,它是有效的)。

What I don't understand is how 'bit--' can be an exit condition. Please help me understand how this code works (I tested it, and it is valid).

感谢您。

推荐答案

在C,零值评估在布尔环境中为假。因此,当位 - 计算结果为 0 ,在循环的上下文中的计算结果为假,并终止循环。

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");
}

据输出假,因为 - X 的计算结果为0,这是在布尔环境中假

It will output "False", because --x evaluates to 0, which is "false" in a boolean context.

这篇关于了解for循环的退出条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆