# 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
Its because after the
if
thegoto
statement is again executed and then the value ofa
has already become other than0
. Now, again you get thegoto
statement and thereforeif
goes on executing and printing negative values.Look at it this way :-
The statement
is executed only when condition in
if
is true. TRUE here refers to anything not equal to0
so, theprintf
is not executed whena
is0
, while it executes for any other value. Now,a--
andgoto
are executed outsideif
so they are executed again and again making the condition inif
true always and negative values are printed infinitely.Nevertheless,
My question is , why are you using
goto
?etc.
Therefore it will display numbers in descending order, except 0 which will not display.
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 print0
, but your question is really why the program loops infinitely.This is because the
if
-body only contains the print statement. So whena
reaches 0 it isn't printed but the linesare 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 whena != 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 awhile
loop:(The braces around the
while
-body are not even strictly necessary here, but just good practice)