r/programminghomework • • Mar 21 '18

Please help me understand this problem

I am studying about pointers and for practice I wrote this snippet.

#include <stdio.h>
int disp(int *a)
{
    int b;
    if(*a==10)
        return 0;    
    printf("%d",*a);
    *a += 1;
    b=disp(&(*a));
    printf("%d",b); 
                    //note the output of first code, then add space(s) 
                    //between %d and " in the second print statement 
                    //Or, you can write \n any number of times instead, and then run the code.
                    //The output changes somehow.
}
int main()
{
    int a=2;
    disp(&a);
    return 0;
}

When I run the program the way I have mentioned in the comment in code, it gives different output somehow. And I can't understand why. Please help me understand why is this happening?

2 Upvotes

4 comments sorted by

View all comments

Show parent comment

1

u/duplicateasshole Mar 26 '18

final output is the length of the string passed to your second printf.

The first output of second printf() is always 0 for this snippet, which is expected because in the final call to disp(), the if condition is true, and therefore 0 is returned to variable b in the final call. But the previous calls to disp() cannot return 0 that was mentioned in the if statement because the condition returned false at the time the function was called.

Now based on your explanation, should I understand that if the argument in printf() has no value, it just returns the length of the argument?