I'm currently preparing for gate; I have come across a question
#include<stdio.h>
main()
{
static int var=6;
printf("%d\t",var--);
if(var)
main();
}
The output is 6 5 4 3 2 1
I wanna know why it terminated after 1?
I'm currently preparing for gate; I have come across a question
#include<stdio.h>
main()
{
static int var=6;
printf("%d\t",var--);
if(var)
main();
}
The output is 6 5 4 3 2 1
I wanna know why it terminated after 1?
An if
statement always tests to see if the expression inside the parentheses evaluates to true.
In this case, var
is an positive integer, so it evaluates to true
. Since 0 always evaluates to false
, as soon as var = 0
the if
statement evaluates to false
and the loop exits.
Note that if(var)
is not specific to C (re the question title), it applies to many languages.
if (var)
checks whether var
is not zero! If var
is zero it finish.