-1
#include<stdio.h>
int main()
{
    static int s;
    ++s;
    printf("%d",s);
    if(s<=3)
        main();
    printf("%d",s);

}

I'm getting output 12344444 but need only 12344. Can anyone please explain why this problem arises and provide solution?

DeiDei
  • 10,205
  • 6
  • 55
  • 80

1 Answers1

2
#include<stdio.h>
int main()
{
    static int s;
    ++s;
    printf("%d",s); // this printf is called and will print each
                    // number as the recursion is called down
    if(s<=3)
        main();
    printf("%d",s); // <<-- this is why
                    // this one is called as the recursion functions
                    // return so it will be called with the highest 
                    // number as many times as there were recursion.

}

To get what you want try

  #include<stdio.h>
    void recursive()
    {
        static int s;
        ++s;
        printf("%d",s); // this printf is called and will print each
                        // number as the recursion is called down
        if(s<=3)
            recursive();
        else 
            printf("%d",s); // call only if s > 3 
    
    }

    int main()
    {
       recursive();
    }
Rob
  • 2,618
  • 2
  • 22
  • 29
  • 2
    Actually, the value of `s` will *always* be > 3 when the second `printf` statement is encountered. What your comment there should say is "call only if no recursion happened". – Adrian Mole Jun 27 '20 at 12:08
  • @AdrianMole yes. but I was writing my comment as a logical compliment of the s<=3 condition :) – Rob Jun 27 '20 at 12:09
  • 1
    I appreciate that. But the OP's problem was the printing of the three extra `4` values. – Adrian Mole Jun 27 '20 at 12:11
  • @AdrianMole you win :) – Rob Jun 27 '20 at 12:11
  • 2
    @TedLyngmo it might be unwise, but not illegal in C. Its legality is implied in "**5.1.2.2.3 Program termination** 1 If the return type of the main function is a type compatible with int, a return ***from the initial call*** to the main function is equivalent to calling the exit function." – Weather Vane Jun 27 '20 at 12:22
  • 1
    @WeatherVane Correct - I've removed my comment and upvoted yours. I just browsed through the current C standard and found no support at all for my statement. – Ted Lyngmo Jun 27 '20 at 12:29
  • 1
    @TedLyngmo I admit I had to too. Would you prefer to me delete the comment? – Weather Vane Jun 27 '20 at 12:30
  • 1
    Guys leave the info here. :) that way we can all benefit from your research – Rob Jun 27 '20 at 12:31
  • 2
    @WeatherVane No, your comment is very good and saves people like me (who thought that it _is_ illegal) a lot of time. – Ted Lyngmo Jun 27 '20 at 12:32
  • 1
    @WeatherVane And make you guys look like superstars!!! Your response to new information was commendable and should be an example to others. – Rob Jun 27 '20 at 12:34