Reversing a string without two loops?

Assuming you can't use functions to get the string length and you want to preserve the second loop I'm afraid this is the shortest way.

Just as a side-note though: this code is not very safe as at for(int i=0; in[i] != '\0'; i++) you are not considering cases where the argument passed to parameter in is not a valid C string where there isn't a single \0 in all elements of the array pointed by in and this code will end up manifesting a buffer over-read at the first for loop when it will read beyond in boundaries and a buffer overflow in the second for loop where you can write beyond the boundaries of out. In functions like this you should ask the caller for the length of both arrays in and out and use that as a max index when accessing them both.

As pointed by Rishikesh Raje in comments: you should also change the exit condition in the second for loop from i <= string_length to i < string_length as it will generate another buffer over-read when i == string_length as it will access out by a negative index.


void reverse(char *in, char *out) {

    static int index;
    index = 0;

    if (in == NULL || in[0] == '\0')
    {
        out[0] = '\0';
        return;
    }
    else
    {
        reverse(in + 1, out);
        out[index + 1] = '\0';
        out[index++] = in[0];
    }
}

With no loops.

This code is surely not efficient and robust and also won't work for multithreaded programs. Also the OP just asked for an alternative method and the stress was on methods with lesser loops.

Are there other approaches to doing a reverse, or is this the basic one

Also, there was no real need of using static int. This would cause it not to work with multithreaded programs. To get it working correct in those cases:

int reverse(char *in, char *out) {

    int index;

    if (in == NULL || in[0] == '\0')
    {
        out[0] = '\0';
        return 0;
    }
    else
    {
        index = reverse(in + 1, out);
        out[index + 1] = '\0';
        out[index++] = in[0];
        return index;
    }
}

Tags:

C