On Wed, 14 Mar 2012 21:33:36 -0700 (PDT), somenath
<> wrote:
>
>Hello All,
>
>I am very much confused with the output of the two following programs.
>
>First program
>==================
>#include<stdio.h>
>
>void printd(int n)
>{
> printf("\beginning n = %d\n",n);
I don't understand how the \b at the beginning of your format string
can produce the character b you show in your sample output.
> if (n/10) {
> // n = n/10;
> printd(n/10);
> }
> printf("%c ",((n%10)+'0'));
>
>}
>int main(void)
>{
> printd(123);
> putchar('\n');
> return 0;
>}
>Output
>./a.out
>
>beginning n = 123
Where is that b coming from? It is not in your format string.
>
>beginning n = 12
I don't understand why your code produces double spacing here.
Did you cut and paste your code and output or did you retype it?
>
>beginning n = 1
>1 2 3
>
>Second program
>
>#include<stdio.h>
>
>void printd(int n)
>{
> printf("\beginning n = %d\n",n);
> if (n/10) {
> n = n/10;
> printd(n);
> }
> printf("%c ",((n%10)+'0'));
>
>}
>int main(void)
>{
> printd(123);
> putchar('\n');
> return 0;
>}
>
>Output
>==============================
>beginning n = 123
>
>beginning n = 12
>
>beginning n = 1
>1 1 2
>The only difference between the two program is as follows
>In the first program printd is called with n/10 as argument but in the
>latter after computing n=n/10 printd is being called recursively .
>
>Then why the two program output differently?
>
>So my understanding for this different behaviour as follows.
>
>In case of second program the n=n/10 is changing the original n which
>was pushed to stack . That is
>For printd(123) n is modified to 12
>For printd(12) n is modified to 1
>
>so when if (n /10 ) fails it prints 1(1%10 = 1) , then for the call
>printd(12) , prints 1 (as n which was 12 but latter modified to 1
>so 1%10 =1 ) then similarly it print 12%10 2 for call printd(123)
>
>Please let me know if my understanding is correct ? Please provide
>some inputs.
Your understanding is basically correct except for your references to
the stack. While that may be how your system performs parameter
passing, the language only requires each recursive execution of printd
to have its own private copy of n. If you have optimization turned
on, n could be a register variable. How the system creates each n at
the entry to printd, keeps them separate during execution, and
destroys each n as its function returns is an implementation detail
not addressed by the standard.
--
Remove del for email
|