c - 在 C 编程中退出 while(1) 循环

标签 c while-loop return-value infinite-loop

我正在为我的C 编程课做例子。其中一个例子是:

更新:return 0;break; 之间的区别

#include<stdio.h>
int main()
{

while(1)
{
  printf("Enter number: ");
  scanf("%d", &num);

  if (num==2)
   {
      return 0;
   }
  else
   {
      printf("Num = %d", num);
   }

return 0;
}

我知道 while(1) 是一个无限循环。 为了跳出循环,我通常使用 break;

但是,在这个例子中,当 num=2 时,它会跳出循环。

我不明白 return o; 如何影响 while(1) 循环?

最佳答案

为了更好地向您解释,让我们在您的代码中添加几行:

#include<stdio.h>
int main()
{

    while(1)
    {
        printf("Enter number: ");
        scanf("%d", &num);

        if (num==2)
        {
            return 0;
        }
        else
        {
            printf("Num = %d", num);
        }
     }

     printf ("BYE\n");
     return 0;
}

让我们用 break 代替 return 0;:

#include<stdio.h>
int main()
{

    while(1)
    {
        printf("Enter number: ");
        scanf("%d", &num);

        if (num==2)
        {
            break;
        }
        else
        {
            printf("Num = %d", num);
        }
     }

     printf ("BYE\n");
     return 0;
}

第一个代码的输出不会包含消息“BYE”,而第二个代码会。

所以总结 return 终止函数并且不执行它下面的任何东西,其中 break 终止循环并且程序不执行循环中的剩余行。

关于c - 在 C 编程中退出 while(1) 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50069977/

相关文章:

php - while 循环不会停止遍历数组

PHP while-for 嵌套循环不显示所有 MySQL 结果

java - 在 while 循环中更新字符串 N 秒

shell - 如何检查 shell 指令的返回值

c - 以下数组读取函数有什么问题?

c - 如何在 FreeBSD 中调试 malloc/memleaks

c++ - C++中基于时区的时间

c - 存储大小未知

java - 方法始终返回零

C++ 返回值显示 -858993460