为什么这个循环在c中运行无限次? [英] why this loop is running infinite times in c?

查看:161
本文介绍了为什么这个循环在c中运行无限次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在C编程中试验一个代码。并来了解一个奇怪的行为。
那么...因为我不是C上的专家,所以我不知道它是奇怪的还是正常的。

基本上我的问题是关于以下两行代码之间的区别: -

  char a ='h'; //这里变量a不是char数组

和$ /

  char a ='hi'; //这里的变量a也不是一个char数组(不知道编译器是否把它当作一个数组,但至少我没有这样声明)

我使用了下面的代码:

第一个: -

  char a = 0; $; 
for(; a<'hi'; a ++)
{
printf(%d = hello world \\\
,a);

$ / code>

第二:

  char a; (a ='h'; a<'hi'; a ++)
{
printf(%d = hello world \\\
,a)的


$ / code>

上面提到的两个循环都会一直运行,



有人可以告诉我为什么吗?

我可能会错过一个非常基本的编程概念。请帮助我们

解决方案

那是因为'hi' int 不是 char 。它也解析为值26729.但最可能的循环变量(假设 char 为1字节类型,字节为8位)受127限制,之后溢出。注意这个:

  char a = 0; 


char m ='hi'; (; a {
printf(%d = hello world \\\
,a)
;

$ / code $


可以工作,因为'hi'将被强制转换为char(105)。
$ b

'hi'是一个多字符字面值。在编程中并不常见,它是C99标准的一部分的不为人知的C特征。更多关于它们的信息: http://zipcon.net/~swhite/ docs / computers / languages / c_multi-char_const.html


I was just experimenting a code in C programming. and came to know a strange behavior. Well... Since i am not an expert on C, so i don't know whether its strange or normal.

Basically my question is all about the difference between the following two lines of code:-

char a = 'h'; // here variable a is not an array of "char"

and

char a = 'hi'; //here variable a is not an array of "char" as well (i don't know if compiler assumes it as an array or not but , at least i didn't declared it that way )

I used the following codes

first:-

char a =0;
for(;a<'hi';a++)
{
    printf("%d= hello world \n",a);
}

second:-

char a;
for(a='h';a<'hi';a++)
{
    printf("%d= hello world \n",a);
}

both of the above mentioned loops keep running forever,

Can somebody tell me why so ?

I might be missing a very basic concept of programing. please help me guys

解决方案

That is because 'hi' has type int not a char. It also resolves to value 26729. But loop variable most likely (assuming char is 1-byte type and byte has 8 bits) is limited by 127 and after that overflows.

Note that this:

char a =0;
char m = 'hi';
for(; a < m; a++)
{
    printf("%d= hello world \n",a);
}

will work because 'hi' is will be coerced to char (105).

'hi' is a multi-character literal. It is not common practice in programming, it is "less known" C feature which became part of C99 standard. More information about them: http://zipcon.net/~swhite/docs/computers/languages/c_multi-char_const.html

这篇关于为什么这个循环在c中运行无限次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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