using goto keyword in C [closed]

2019-09-22 12:52发布

问题:

# 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.



标签: c goto