I saw a C code like this:
#include <stdio.h>
void main ()
{
static int ivar = 5;
printf ("%d", ivar--);
if (ivar)
main ();
}
which outputs :
54321
I’m a novice in C and I guess until the condition fails the main method is called again and again. Since I’m a novice in C, is it good practice to call the main function more than once as in the above case? Are there any real world cases, where this kind of code is very useful?
Thanks in advance.
A while-loop would be more suitable. Recursion makes sense when, with each recursion, you are doing a different job — typically a smaller one.
What this code is really doing is demonstrating function-local static variables: the
ivaris only initialised in the first call ofmain. Each time you recurse, it is decremented despite theivar=5statement.mainhas a special meaning. Idiomatically, it should initialise the environment and then call some other function which drives the application logic.An optimising compiler might well transform that code into an iterative version anyway.