gpt4 book ai didi

c - 为什么这个循环在 c 中运行无限次?

转载 作者:太空狗 更新时间:2023-10-29 14:54:00 25 4
gpt4 key购买 nike

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

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

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

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 )

我使用了以下代码

首先:-

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

第二个:-

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

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

谁能告诉我为什么会这样?

我可能缺少一个非常基本的编程概念。请大家帮帮我

最佳答案

那是因为 'hi' 的类型是 int 而不是 char。它还解析为值 26729。但是循环变量最有可能(假设 char 是 1 字节类型并且字节有 8 位)被限制为 127,然后溢出。

请注意:

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

将起作用,因为 'hi' 将被强制转换为 char (105)。

'hi' 是一个多字 rune 字。这在编程中并不常见,它是“鲜为人知”的 C 特性,已成为 C99 标准的一部分。有关它们的更多信息:http://zipcon.net/~swhite/docs/computers/languages/c_multi-char_const.html

关于c - 为什么这个循环在 c 中运行无限次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28189073/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com