#include <stdio.h> void main(){ static int n=7; if(n){ n--; main(); printf("%d",n); } } Sol: I was trying to trace the recursion. In my logic answer should be 1234567, but the answer is 000000. My question is how to trace this recursion?
That is because you are calling main before printing.
if you do:
#include <stdio.h> void main(){ static int n=7; if(n){ n--; // main(); printf("%d",n); main(); } return; } You will get the output: 6543210
But in your case, it will print only when the value of n is 0. And since 7 print is pending therefore 0000000
The best way to trace it probably is using gdb to follow it along.
If you declare n as static, it's value would be preserved across function calls. Note that you are calling printf after the recursive step (calling main). This causes printf to see the value of n after all the calls to main.
Think of this sequence, executing with n = 2
if (n) // first time, n == 2. n--; // n == 1 main(); if (n) // second time, n == 1 n--; main(); if (n) // third time, n == 0, fails printf("%d",n); // n == 0. printf("%d",n); // n == 0.
nisstatic. So there's only one of it. And by the time any of themain's start printing it, all the subtractions have been done.