Pergunta

void reverse(char *s,int j,int i) {
      printf("%d\t%d\n",i,j);
      if(i<j) {
        swap(s, i, j);
        reverse(s,--j,++i);
      }
    }

I read on Stack Overflow that using the postincrement operators in the function call can pose problems but does the use of the preincrement in function calls is also wrong??

Please help.

Foi útil?

Solução

Increment operators cause undefined behavior if they modify the same variable in the same sequence point (statement). For example if you call a function like this: foo(++i, ++i) the C standard doesn't say in which order the increments should be performed, and you can't predict what will be passed to the function.

This is not the case here, so your program's semantics are well defined. That is, i and j are incremented and then their values are passed to the function.

Outras dicas

The only problem I see with the function you have written is that you are using the condition i!=j and this can cause problems with strings of even length.
Consider the case of string length=4, you will have the function calls as reverse(s,3,0)-> reverse(s,2,1)->reverse(s,1,2).. and so you can see 'i' will never be equal to 'j' and the loop won't terminate, instead when j becomes negative and i becomes greater than the length of the string, you can possible have a run time error for accessing parts of memory you are not allowed to. Hope this made sense. :)

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top