Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

strcmp — comparing strings

strcmp compares the contents of two null-terminated strings. Its result describes equality or ordering.

Version: C23; repository compiler flag, production runtime not attested

Syntax

#include <string.h>
int strcmp(const char *s1, const char *s2);

strcmp from <string.h> returns an int: negative, zero, or positive when s1 is respectively less than, equal to, or greater than s2. Test its sign, not specific values -1 and 1.

The first differing character pair, interpreted as unsigned char, determines ordering. A shorter identical prefix is smaller. This is not linguistic ordering; use strcoll for locale-sensitive comparison.

Both arguments must point to valid strings terminated by \0. Null pointers or an inaccessible terminator cause undefined behavior. Embedded \0 ends the string.

Test content equality with strcmp(s1, s2) == 0; s1 == s2 compares pointers.

Examples

#include <stdio.h>
#include <string.h>

int main(void)
{
    printf("equal: %d\n", strcmp("cat", "cat") == 0);
    printf("prefix: %d\n", strcmp("cat", "cats") < 0);
    printf("reverse: %d\n", strcmp("cats", "cat") > 0);
    return 0;
}

Result

equal: 1
prefix: 1
reverse: 1

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources