Home > Software engineering >  Why am I getting an error in this C program?
Why am I getting an error in this C program?

Time:09-28

I am new to C programming but I stumbled on this code

int print(int nb)
{
    if (nb < 0) 
    {
        return (0);
    }
    printf("%d", nb   print(nb - 1));
    nb --;
    return (nb);
}

int main(void)
{
    print(4);
    return (0);
}

I ran the code and it gave me an output of 00246 why is that the output that, looking at it logically, the answer is not suppose to start with a 0

CodePudding user response:

print(4) -> print(3) -> print(2) -> print(1) -> print(0) -> print(-1)

print(-1) stops the recursion returning 0, thus a call to printf() is emitted with 0 0, which is 0.

print(0) ends with -1 as value, and a call to printf() with 1 -1 is emitted, which is 0.

etc.

  •  Tags:  
  • c
  • Related