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
solved using goto keyword in C [closed]