using goto keyword in C [closed]

守給你的承諾、 提交于 2019-12-13 23:32:07

问题


# 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

回答1:


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)




回答2:


Its because after the if the goto statement is again executed and then the value of a has already become other than 0 . Now, again you get the goto statement and therefore if goes on executing and printing negative values.

Look at it this way :-

The statement

printf("%d\n",a);

is executed only when condition in if is true. TRUE here refers to anything not equal to 0 so, the printf is not executed when a is 0, while it executes for any other value. Now, a-- and goto are executed outside if so they are executed again and again making the condition in if true always and negative values are printed infinitely.

Nevertheless,

My question is , why are you using goto?




回答3:


if a==1 -> Evaluates to TRUE
if a==0 -> Evaluates to FALSE
if a==-1 -> Evaluates to TRUE

etc.

Therefore it will display numbers in descending order, except 0 which will not display.



来源:https://stackoverflow.com/questions/17633405/using-goto-keyword-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!