-1

When i write copy ( s1++, s2++ ) instead of copy ( ++s1, ++s2 ) nothing happens.What's the problem?

#include<stdio.h>

void copy ( char *, char * );

int main ( void )
{
   char st[] = "hello";
   char st2[10];
   copy ( st, st2 ); 
   printf ( "%s", st2 );
}

void copy ( char *s1, char *s2 )
{
    *s2 = *s1;
    if ( *s1 == '\0' )
    {
        return;
    }
    copy ( ++s1, ++s2 );
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
dumb
  • 21
  • 3
  • 2
    `copy ( s1++, s2++ )` will repeatedly pass the *same* pointer values to the recursive calls of `copy`. That is, it is an infinete recursion doing the same thing over and over again (until the program presumably gets a stack overflow). – kaylum Jun 19 '22 at 21:25
  • See [What is the difference between ++i and i++?](https://stackoverflow.com/questions/24853) – Steve Summit Jun 19 '22 at 21:30
  • 3
    I'd say it would be clearer to write `copy (s1+1, s2+1);` as the recursive call – Steve Summit Jun 19 '22 at 21:31

1 Answers1

0

From the C Standard (6.5.2.4 Postfix increment and decrement operators)

2 The result of the postfix ++ operator is the value of the operand. As a side effect, the value of the operand object is incremented (that is, the value 1 of the appropriate type is added to it).

So using the post-increment operator you are calling recursively the function with the same values of the pointers.

This call

copy ( s1++, s2++ );

has the same effect as

copy ( s1, s2 );
++s1;
++s2;

Using the post-increment operator the function could be defined for example the following way.

void copy( const char *s1, char *s2 )
{
    if ( ( *s2++ = *s1++ ) ) copy( s1, s2 );
}

As for the prefix increment operator then according to the C Standard (6.5.3.1 Prefix increment and decrement operators)

2 The value of the operand of the prefix ++ operator is incremented. The result is the new value of the operand after incrementation.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335