/**********************************
* Written by Mathias Van Malderen *
**********************************/

void reverse(char p[])
{
     int len=strlen(p);
     char t;
     for(int i=(--len), j=0; i>len/2; i--, j++)
     {
          // exchange elements
          t=p[i];
          p[i]=p[j];
          p[j]=t;
     }
}

For C style strings there is <string.h>'s _strrev() and for C++'s strings there's <algorithm>'s reverse().
_strrev() is generally provided in most compilers.

This is how it would look like if you asked me to rewrite it:

void reverse(char *p)
{
    char *q = p + strlen(p) - 1;

    for(; p < q; p++, q--)
    {
        char c = *p;
        *p = *q;
        *q = c;
    }
}

(no NULL-pointer check included).

I would do this a bit different:

void reverse(char p[])
{
      int len=strlen(p);

      for(int i=0, i<len/2; i++)
     {
          // exchange elements
          p[i]^=p[len - i - 1];
          p[len - i - 1]^=p[i];
          p[i]^=p[len - i - 1];
      }
}

Edited 3 Years Ago by Dani: Formatting fixed

Your code snippet can be shortened tux...here it goes:

void reverse(char p[])
{
     int len=strlen(p);
     for(int i=len-1, j=0;j<i; i--, j++)
     {
          // exchange elements
          p[i]^=p[j]^=p[i]^=p[j];
     }
}

Try it and do tell me what do you think...???

Edited 7 Years Ago by csurfer: n/a

Sorry about the reply... I didn't see it was a 6 month old thread resurrected... just answered it... ;)

All I wanted just reduce the number of local variables.
Your line “p^=p[j]^=p^=p[j];” in most of compilers has “undefined behaviour”.
Just try to swap to integers a = 0x55 and b = 0xAA your way (a ^= b ^= a ^= b;) using different compilers.

>Sorry about the reply... I didn't see it was a 6 month old thread resurrected... just answered it...
Never mind, any input is welcome.

>All I wanted just reduce the number of local variables.
Yes, I see, though the algorithm of reversing the string is basically the same, I hadn't thought of the the fact that I could use XOR-operations to swap the values without having to use a temporary variable.

Nice suggestion :)

@vitkaodessit: please post your code using code tags the next time.

Edited 7 Years Ago by mvmalderen: n/a

>>All I wanted just reduce the number of local variables.
>Yes, I see, though the algorithm of reversing the string is basically the same,
>I hadn't thought of the the fact that I could use XOR-operations to swap the values without having to use a temporary variable.

>Nice suggestion

Although this eliminates the extra variable, it can cause undefined behavior. For some reason, some teachers insist on learning their student this 'xor swap method', but I would strongly advice against it.

Edited 7 Years Ago by Nick Evan: n/a

The article starter has earned a lot of community kudos, and such articles offer a bounty for quality replies.