使用转到关键字用C [英] using goto keyword in C

查看:181
本文介绍了使用转到关键字用C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 #包括LT&;&stdio.h中GT;诠释的main()
{
  INT 1 = 5;
  开始:
  如果一个)
       的printf(%d个\\ N,一);
   一个 - ;
   转到开始;
   返回0;
 }

当一个变为0,然后,如果为什么输出将是在这个code手段infinty情况不会再执行

输出 -

  5
 4
 3
 2
 1
 0
-1
-2
等等没完没了


解决方案

如果该程序确实会打印出 0 为你那么有可能是你的编译器一个严重的问题(甚至你的机器...)。我怀疑的是,它不打印 0 ,但你的问题实在是为什么程序无限循环。

这是因为如果 - 身体只包含print语句。因此,当 A 到达0不打印它,但线

  A--;
转到开始;

仍在执行。机器会服从,回去开始并继续循环。最快的解决方法是把周围的括号的所有的你想要执行的语句时, A = 0

 如果(一){
    的printf(%d个\\ N,一);
    一个 - ;
    转到开始;
}返回0;

这将会使程序只循环直到 A 0,之后返回。

但真正的问题是:不使用转到(本)!这是使用 个完美的局面,而循环

 而(A  - ){
    的printf(%d个\\ N,一);
}返回0;

(周围的括号中的,而 - 身体甚至不是绝对必要在这里,只是很好的做法)

# include <stdio.h>

int main()
{
  int a=5;
  begin:
  if(a)
       printf("%d\n",a);
   a--;
   goto begin;
   return 0;
 }

When a becomes 0 then if condition will not execute then why the output is going to be infinty in this code means

output -

 5
 4
 3
 2
 1
 0
-1
-2
and so on endless

解决方案

If the program really does print 0 for you then there might be a serious problem with your compiler (or even your machine...). My suspicion is that it doesn't print 0, but your question is really why the program loops infinitely.

This is because the if-body only contains the print statement. So when a reaches 0 it isn't printed but the lines

a--;
goto begin;

are still executed. The machine will obey, go back to begin and the loop continues. The quickest fix is to put braces around all the statements you want executed when a != 0:

if(a){
    printf("%d\n",a);
    a--;
    goto begin;
}

return 0;

This will make the program only loop until a is 0, after which it returns.

But the real problem is: don't use goto (for this)! This is a perfect situation to use a while loop:

while(a--){
    printf("%d\n", a);
}

return 0;

(The braces around the while-body are not even strictly necessary here, but just good practice)

这篇关于使用转到关键字用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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