Skip to content

Reverse String

A C function that reverses a string in place using the XOR swap trick.

Published Aug 10, 1997

The textbook in-place string reversal: two pointers start at each end and walk toward the middle, swapping characters on the way. The interesting detail is the swap itself - three XOR operations instead of a temporary variable, which was a favorite pre-modern-C idiom for saving one register (and which you should not use in safety-critical code today, since XOR-swapping a variable with itself yields zero). Handles the empty/NULL cases up front and returns the same pointer it was given.

#include <Windows.H>
#include <WindowsX.H>
#include <Stdio.H>
#include <Stdlib.H>

char *StringReverse(char *);

char *StringReverse(char *str)
{
	char *p1, *p2;

	if (! str || ! *str)
		return str;

	for (p1 = str, p2 = str + strlen(str) - 1; p2 > p1; ++p1, --p2)
	{
		*p1 ^= *p2;
		*p2 ^= *p1;
		*p1 ^= *p2;
	}
	return str;
}

////////////////////////////////////////////////////////////////////////

int main()
{

	printf("%s\n",StringReverse("Hello World"));

	return 0;
}

The loop condition p2 > p1 (rather than >=) is what makes odd-length strings come out right - the middle character is simply left alone. If you want to keep the XOR flavor but avoid the self-swap hazard, guard with if (*p1 != *p2) before the three lines.

An unhandled error has occurred. Reload 🗙