为什么在C语言中永远计数一个无符号的int循环? [英] Why does counting down an unsigned int loop forever in C?
本文介绍了为什么在C语言中永远计数一个无符号的int循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下代码在无限循环中运行. 将'i'初始化为值1,然后将其与0进行比较.
The below code runs in an infinte loop. 'i' has been intialised with the value 1 and then compared with 0.
因此,printf()stmt应该执行一次,但可以无限次运行.
So printf() stmt should execute once but it runs infinetly.
unsigned int i = 1;
for (; i >= 0; i--) {
printf("Hello: %u\n",i);
}
请解释这种行为.
推荐答案
正如其他答案所说,这是因为它是未签名的.我将告诉您一种使用无符号整数 进行操作的优雅方法.
As other answers said, it's because it's unsigned and all. I will tell you an elegant way to do what you want to do with an unsigned integer.
unsigned int i=10;
while(i --> 0) printf("Hello:%u\n", i+1);
此-->
有时也称为 运算符.但这实际上只是--
和>
.如果您更改间距,则会得到
This -->
is referred to sometimes as the goes to operator. But it's in fact just --
and >
. If you change the spacing, you'll get
while( i-- > 0 )
My2c
这篇关于为什么在C语言中永远计数一个无符号的int循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文