Darshan
Darshan

Reputation: 13

Printing a recursive function returned value when the function contains printf

#include <stdio.h>

int c=0;

int check (int c)
{
    c=c+1;
    if (c<6)
        return check(c);
    printf("%d\n", c);
}

int main()
{
    printf("%d\n",check(c));
}

The above code gives me

6
2

as the output. 6 is from the printf function inside the check function but I did'nt get why 2. If I remove the printf function inside the check function I get

5

as the output. Can anyone explain why this happens?

Upvotes: 1

Views: 368

Answers (2)

Nik
Nik

Reputation: 1870

I made a few modifications to your posted code so that it becomes obvious what is happening. It looks like the compiler outsmarted you, and prepended return in front of printf("%d\n", c); So the 2 that you are seeing is the number of characters printed when you print 6\n on the last iteration of check(). The 2is then passed all the way down the stack to the original call inside the main, eventually ending up on your Console window. See this reference

[printf returns the] number of characters transmitted to the output stream or negative value if an output error or an encoding error (for string and character conversion specifiers) occurred.

Consider the following code. It exhibits identical behaviour to your posted code.

#include <stdio.h>

int check(int c)
{
    int ret = 0;
    c = c + 1;
    if (c < 6)
    {
        ret = check(c);
        return ret;//helps inspect ret
    }
    //looks like the compiler inserts that return statement 
    ret = printf("%d\n", c);// 2 <- number of characters in "6\n".
    return ret;
}

int main()
{
    int c = 0;
    int ret = 0; 
    ret = check(c);//ret comes out == 2. This is the return value of printf
    printf("%d\n", ret);
    getchar();
    return 0;//don't forget this guy!
}

Disclaimer: Even though it appears that this is what is happening, and most likely it probably is, It is not a shortcut and I would not count on this happening every time. The behaviour is still undefined! The best thing to do is to return from functions normally.

Upvotes: 0

user2736738
user2736738

Reputation: 30926

You are invoking undefined behavior. So it behaves oddly.

You must have a proper return statement in the check function as you are supposed to return an int.

Also having printf or not having it - doesn't change anything- it's still UB.(in this case)

Upvotes: 1

Related Questions