Fast string comparison for microcontrollers (C/C++)

This short article presents trivial but fast and memory efficient function to compare two strings. Function returns “0” (zero) on success (strings are the same), otherwise function returns the position where different characters occurred.

Example code

#include <stdint.h>
#include <assert.h>

static int8_t
xstrcmp(const char *s1, const char *s2)
    while(*s1 != '\0' && *s1 == *s2) {s1++; s2++;}
    return (*s1 - *s2);

    assert(xstrcmp("test", "test") == 0); // the same
    assert(xstrcmp("test", "123") != 0); // different
    return (0);

One thought on “Fast string comparison for microcontrollers (C/C++)

  1. This assumes s1 string to be longer than s2. Otherwise you would have to test for string terminator even for s2.

Leave a Comment