Vladimir
Vladimir

Reputation: 15

Print reverse of a string using recursion

This code works:

 void reverse(char *str)
{
   if(*str) 
   {
   reverse(str+1);
   printf("%c", *str);
  }
}

But, if i change reverse(str+1) with reverse(++str), it doesn't print first character.

In: Geeks

Out: skee
I don't know why.

Upvotes: 0

Views: 69

Answers (2)

Abdul Ahmad
Abdul Ahmad

Reputation: 10021

++str increments first then prints, you need str++

Upvotes: 0

furkle
furkle

Reputation: 5059

Because you're altering the pointer given to you in the very first call of the method, so when it finally gets around to printing itself out and completing the execution, the index has already been incremented to the second character.

In the first case, str+1, str isn't being modified at all, so the very last printf just prints the first character.

Keep in mind that the prefix and postfix ++ actually change the value of the variable.

Upvotes: 1

Related Questions