Although it may result in more readable code, I'm using GCC, and profiling shows that
memcpy (not "memcall" I assume
) is faster than direct assignment in this case. For larger strings, I'd rather not sacrifice performance in a handshake for slightly better readability.
GCC replaces an assignment operation by a call to any library function of its liking, but this doesn't guarantee that it is better necessarily, and nor would it be viable to prove or disprove, however, it would also be rather difficult with compiler optimization. memcpy is also designed to be the most efficient way of copy blocks of memory for C..
memcpy is also much safer in other cases that do not necessarily apply here, but for instance in structs where unaligned exceptions can occur with unaligned memory, memcpy will be much faster at the reduction in cost of the exception.
All in all, I see no reason for changing memcpy out with direct assignment here. There is no point.
If somebody doesn't like memcpy, then fine:
void reverse_str_recur(char *s, int lower_index, int upper_index)
{
if (upper_index <= lower_index) return;
*(s + lower_index) = s[upper_index];
*(s + upper_index) = s[lower_index];
reverse_str_recur(s, upper_index - 1, lower_index + 1);
}
But I'll stick with memcpy.
The other option would be memmove:
void reverse_str_recur(char *s, int lower_index, int upper_index)
{
if (upper_index <= lower_index) return;
memmove(s + lower_index, s + upper_index, 1);
memmove(s + upper_index, s + lower_index, 1);
reverse_str_recur(s, upper_index - 1, lower_index + 1);
}
However I could've also reduced my original memcpy version with:
void reverse_str_recur(char *s, int lower_index, int upper_index)
{
if (upper_index <= lower_index) return;
memcpy(s + lower_index, s + upper_index, 1);
memcpy(s + upper_index, s + lower_index, 1);
reverse_str_recur(s, upper_index - 1, lower_index + 1);
}
*EDIT: New version
#include <stdio.h>
#include <string.h>
void reverse_str_recur(char *s, int lower_index, int upper_index)
{
if (upper_index <= lower_index) return;
memcpy(s + lower_index, s + upper_index, 1);
memcpy(s + upper_index, s + lower_index, 1);
reverse_str_recur(s, upper_index - 1, lower_index + 1);
}
#define REVERSE_STRING(s) (reverse_str_recur(s, 0, strlen(s) - 1))
int main()
{
char str[] = "12345";
printf("Original: %s\n", str);
REVERSE_STRING(str);
printf("Reversed: %s\n", str);
}