简体   繁体   中英

C - Reversing a sentence - Recursion - Without Array

void reverse()
{
    char c;
    scanf("%c", &c);
    if(c!='\n')
    {
        reverse();
        printf("%c", c);
    }
}

When 'c==\\n', the program doesn't even get inside the 'if' block. Then how does it print the converted sentence in the end. Please explain where the 'return' happens and also to where it gets returned.

当'c == \\ n'时,它将是递归的结尾,该函数将不再进一步调用自身并返回到最后一个调用,该调用在'printf(“%c”,c)'行中继续,从而打印字符串的最后一个字符,然后返回到第二个最后一个调用,依此类推。

Let's run the code by hand. Imagine we input "foobar" . We'll right down every instruction the computer processes. If we recurse, we'll just indent as we keep track of things. If we do that, we can see the sequence of instructions executed is:

scanf() // reads 'f'
if ('f' != '\n')
  scanf() // reads 'o'
  if ('o' != '\n')
    scanf() // reads 'o'
    if ('o' != '\n')
      scanf() // reads 'b'
      if ('b' != '\n')
        scanf() // reads 'a'
        if ('a' != '\n')
          scanf() // reads 'r'
          if ('r' != '\n')
            scanf() // reads '\n'
            if ('\n' != '\n')
          printf('r')
        print('a')
      print('b')
    print('o')
  print('o')
print('f')

Each indentation is a recursive call to reverse() . As you can see, the sequence of printf() commands are the reverse of the input "foobar" .

Hopefully this gives some insights as to how it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM