0

I really don't understand why in the first case code doesn't work and in the second case code works fine. Differences between the first case and the second one is that in the first case i wrote exchange algorithm in the one line, and in the second case i wrote the same exchange algorithm in the several ones.

For compile please run: g++ -DDEBUG -o str_reverce str_reverce.cpp

Sorry for my English.

first case:

#include <iostream>

using namespace std;

#ifdef DEBUG
#define debug(arg) cout << __FUNCTION__ <<  ":" << __LINE__ << ": " << arg << endl;
#else
#define debug(arg)
#endif

char *str_reverse(char *str)
{
        if (str == NULL) {
                debug("wrong arg!");
                return NULL;
        } 

        debug("before: " << str);

        unsigned int i = 0, j = 0;

        while (str[i] != '\0') // Find out string length
                ++i;

        debug("string length: " << i);

        if (i <= 1) {
                debug("string is too small!");
                return str;
        }  

         // a = b^(b^a)
        // b = a^(b^a)

        for (j = 0; j < i/2; j++) {
                /*str[i-j-1]=str[i-j-1]^str[j];
                str[j]=str[j]^str[i-j-1];
                str[i-j-1] = str[i-j-1]^str[j];*/
                str[i-j-1] = str[i-j-1]^(str[j]=str[j]^(str[i-j-1]=str[i-j-1]^str[j]));
        }

        debug("after: " << str);

        return str;
} 

int  main(int argc, char *argv[])
{
        char str[] = "0123456789";
        str_reverse(str);
}

second case:

#include <iostream>

using namespace std;

#ifdef DEBUG
#define debug(arg) cout << __FUNCTION__ <<  ":" << __LINE__ << ": " << arg << endl;
#else
#define debug(arg)
#endif

char *str_reverse(char *str)
{
        if (str == NULL) {
                debug("wrong arg!");
                return NULL;
        } 

        debug("before: " << str);

        unsigned int i = 0, j = 0;

        while (str[i] != '\0') // Find out string length
                ++i;

        debug("string length: " << i);

        if (i <= 1) {
                debug("string is too small!");
                return str;
        }  

         // a = b^(b^a)
        // b = a^(b^a)

        for (j = 0; j < i/2; j++) {
                str[i-j-1]=str[i-j-1]^str[j];
                str[j]=str[j]^str[i-j-1];
                str[i-j-1] = str[i-j-1]^str[j];
                //str[i-j-1] = str[i-j-1]^(str[j]=str[j]^(str[i-j-1]=str[i-j-1]^str[j]));
        }

        debug("after: " << str);

        return str;
} 

int  main(int argc, char *argv[])
{
        char str[] = "0123456789";
        str_reverse(str);
}

Thanks!

scopichmu
  • 135
  • 11

0 Answers0