What does strncmp actually do?

strncmp compares the first two characters in the strings. (When comparing characters, it uses their values as unsigned char, even though they are passed via pointers to char.) If the characters differ or either is a null character:

  • If the character from the first string is greater than the character from the second, strncmp returns a positive value.
  • If the first is less than the second, strncmp returns a negative value.
  • Otherwise (the characters are both null characters), strncmp returns zero.

If the characters did not differ and neither was a null character, strncmp goes on to compare the following characters in the same way, until n pairs have been compared. If no difference has been found after n pairs have been compared, strncmp returns zero.

Some implementations of strncmp may return the signed difference between the two characters that differed, but this is not required by the C standard. strncmp may simply return +1 and −1 for “greater than” and “less than” or may use other positive and negative values.

Answer from Eric Postpischil on Stack Overflow
🌐
W3Schools
w3schools.com › c › ref_string_strncmp.php
C string strncmp() Function
The strncmp() function compares the first n characters of two strings and returns an integer indicating which one is greater.
🌐
TutorialsPoint
tutorialspoint.com › home › c_standard_library › c strncmp function
C strncmp Function
August 29, 2012 - The C library strncmp() function is used to compare at most a specified number of characters from two null-terminated strings. This string is also known as end of the string i.e.
Discussions

Is strcmp in embedded C safe? If not, what are the usual substitutes?
In your code, you have inputCmd as an array of pointers, which is not what you want. Anyway, ignoring that, strncmp is the "safer" alternative to strcmp. More on reddit.com
🌐 r/embedded
17
9
February 3, 2023
Strcmp function doesn’t work healthy with strings includes blank. How can I handle it? For example when I compare “Hello World” and “Hello” the function’s value is not 0 or 1. I think it is about ‘\0’ but I don’t know how to handle it
The only thing strcmp guarantees is that the return value is zero if the two strings are equal, positive if the first string is greater that the second and negative if the second is greater than the first. If you call strcmp("Hello World", "Hello") one would expect it to return a positive number. What it does is look down the string until it finds the first one that this not the same between the two. In this case it is comparing ' ' with '\0'. ' ' > '\0' so the return is positive. Many versions of strcmp would return the integer value of ' ' there because what it does is something like: while(*ptr1 && *ptr1++ == *ptr2); return *ptr1 - *ptr2; More on reddit.com
🌐 r/C_Programming
12
6
January 15, 2022
What's with all the casting to unsigned char in strcmp.c?
Whether char is signed or unsigned is implementation defined. By explicitly accessing strings as unsigned quantities, the behavior remains consistent across implementations. Imagine comparing two strings "" and "\x80" (remember the implicit null terminators). This hits the c1 == '\0' condition on the first iteration. If c1 and c2 were signed, then that 0x80 byte would be treated as a negative value, and so c1 - c2 would have a positive result. However, as unsigned, 0x80 is positive and c1 - c2 becomes a negative result. The latter is the behavior callers actually want, and using unsigned char explicitly means it's consistent across platforms. That being said, I wouldn't write it this way, and those (unsigned char) casts are entirely redundant. Maintaining the same structure and style, I'd do this instead: int STRCMP (const char *s1, const char *s2) { int c1, c2; do { c1 = *s1++ & UCHAR_MAX; c2 = *s2++ & UCHAR_MAX; if (c1 == 0) return c1 - c2; } while (c1 == c2); return c1 - c2; } The & UCHAR_MAX (read: & 255) does the appropriate truncation on all systems supported by glibc. but every subsequent one is only cast to a normal unsigned char. Because they're not pointers and using const there makes no sense. More on reddit.com
🌐 r/C_Programming
20
20
April 20, 2022
Implementing my own strcmp - have I got it right?
have I got it right? Do all your tests pass? More on reddit.com
🌐 r/C_Programming
21
9
July 16, 2018
Top answer
1 of 2
2

What does strncmp actually do?

strncmp compares the first two characters in the strings. (When comparing characters, it uses their values as unsigned char, even though they are passed via pointers to char.) If the characters differ or either is a null character:

  • If the character from the first string is greater than the character from the second, strncmp returns a positive value.
  • If the first is less than the second, strncmp returns a negative value.
  • Otherwise (the characters are both null characters), strncmp returns zero.

If the characters did not differ and neither was a null character, strncmp goes on to compare the following characters in the same way, until n pairs have been compared. If no difference has been found after n pairs have been compared, strncmp returns zero.

Some implementations of strncmp may return the signed difference between the two characters that differed, but this is not required by the C standard. strncmp may simply return +1 and −1 for “greater than” and “less than” or may use other positive and negative values.

2 of 2
1

strncmp(s1, s2, n) compares up to n characters from the strings pointed to by s1 and s2. It stops if it finds a difference and returns a negative value if the character from s1, converted to an unsigned char is less than the corresponding character from s2 (also converted to an unsigned char) and a positive value it is is greater. Subtracting the values of the differing characters is a handy way to compute a return value with the correct sign.

If no difference was found before the end of both strings or n characters have been processed, whichever comes first, it returns 0.

Your code has some small issues:

  • the pointer arguments should be declared with type const char * and n with type size_t.
  • similarly, i should be defined as a size_t, defining it as an int forces you to use a cast in the comparison and will cause undefined behavior for strings with an identical prefix longer than INT_MAX and a large enough n argument.
  • you should not dereference s1[i] nor s2[i] if n has reached 0, so the test on n should be performed first.
  • the difference should be computed as diff = (unsigned char)s1[i] - (unsigned char)s2[i];
  • note also that on some very exotic platforms, where sizeof(char) == sizeof(int), the subtraction cannot be used as it may wrap around and produce incorrect results.
  • it is preferable to not use names reserved for standard functions for your own versions and it may cause clashes with the compiler's intrinsics.

Here is a modified version:

#include <stdio.h>

int my_strncmp(const char *s1, const char *s2, size_t n) {
    for (size_t i = 0; i < n; i++) {
        int diff = (unsigned char)s1[i] - (unsigned char)s2[i];
        if (diff != 0 || s1[i] == '\0')
            return diff;
    }
    return 0;
}

int main() {
    char s11[] = "abcs";
    char s12[] = "zzfs";
    size_t n = 3;
    printf("   strncmp() -> %d\n", strncmp(s11, s12, n));
    printf("my_strncmp() -> %d\n", my_strncmp(s11, s12, n));
    return 0;
}

The output values may differ but should have the same sign or should both be null.

🌐
GeeksforGeeks
geeksforgeeks.org › c++ › stdstrncmp-in-c
std::strncmp() in C++ - GeeksforGeeks
July 2, 2024 - std::strncmp() function in C++ lexicographically compares not more than count characters from the two null-terminated strings and returns an integer based on the outcome.
🌐
IBM
ibm.com › docs › en › zos › 3.1.0
strncmp() — Compare strings
We cannot provide a description for this page right now
🌐
BeginnersBook
beginnersbook.com › 2017 › 11 › c-strncmp-function
C strncmp() Function with example
September 11, 2022 - #include <stdio.h> #include <string.h> int main () { char str1[20]; char str2[20]; int result; //Assigning the value to the string str1 strcpy(str1, "hello"); //Assigning the value to the string str2 strcpy(str2, "helLO WORLD"); //This will compare the first 3 characters result = strncmp(str1, str2, 3); if(result > 0) { printf("ASCII value of first unmatched character of str1 is greater than str2"); } else if(result < 0) { printf("ASCII value of first unmatched character of str1 is less than str2"); } else { printf("Both the strings str1 and str2 are equal"); } return 0; }
🌐
Cplusplus
cplusplus.com › reference › cstring › strncmp
strncmp - cstring
strncmp · function · <cstring> int strncmp ( const char * str1, const char * str2, size_t num ); Compare characters of two strings · Compares up to num characters of the C string str1 to those of the C string str2. This function starts comparing the first character of each string.
Find elsewhere
🌐
The Open Group
pubs.opengroup.org › onlinepubs › 000095399 › functions › strncmp.html
strncmp
The strncmp() function shall compare not more than n bytes (bytes that follow a null byte are not compared) from the array pointed to by s1 to the array pointed to by s2. The sign of a non-zero return value is determined by the sign of the difference between the values of the first pair of bytes (both interpreted as type unsigned char) that differ in the strings being compared.
🌐
Cppreference
cppreference.com › w › c › string › byte › strncmp.html
strncmp - cppreference.com
June 15, 2023 - #include <stdio.h> #include <string.h> void demo(const char* lhs, const char* rhs, int sz) { const int rc = strncmp(lhs, rhs, sz); if (rc < 0) printf("First %d chars of [%s] precede [%s]\n", sz, lhs, rhs); else if (rc > 0) printf("First %d chars of [%s] follow [%s]\n", sz, lhs, rhs); else printf("First %d chars of [%s] equal [%s]\n", sz, lhs, rhs); } int main(void) { const char* string = "Hello World!"; demo(string, "Hello!", 5); demo(string, "Hello", 10); demo(string, "Hello there", 10); demo("Hello, everybody!"
🌐
Linux Man Pages
man7.org › linux › man-pages › man3 › strncmp.3p.html
strncmp(3p) - Linux manual page
Any conflict between the requirements ... ISO C standard. The strncmp() function shall compare not more than n bytes (bytes that follow a NUL character are not compared) from the array pointed to by s1 to the array pointed to by s2....
🌐
SAS
support.sas.com › documentation › onlinedoc › sasc › doc750 › html › lr1 › z2056678.htm
Function Descriptions : strncmp
strncmp compares two character strings ( str1 and str2 ) using the standard EBCDIC collating sequence. The return value has the same relationship to 0 as str1 has to str2 . If two strings are equal up to the point at which one terminates (that is, contains a null character), the longer string ...
🌐
GeeksforGeeks
geeksforgeeks.org › c++ › difference-strncmp-strcmp-c-cpp
Difference between strncmp() and strcmp in C/C++ - GeeksforGeeks
November 10, 2022 - strcmp compares both the strings till null-character of either string comes whereas strncmp compares at most num characters of both strings. But if num is equal to the length of either string than strncmp behaves similar to strcmp.
🌐
W3Resource
w3resource.com › c-programming › string › c-strncmp.php
C strncmp() function
C strncmp() function (string.h): The strncmp() function is used to compare string1 and string2 to the maximum of n.
🌐
Programiz
programiz.com › cpp-programming › library-function › cstring › strncmp
C++ strncmp() - C++ Standard Library
The strncmp() function in C++ compares a specified number of characters of two null terminating strings. The comparison is done lexicographically.
🌐
Cprogramming
cboard.cprogramming.com › c-programming › 180049-confused-strncmp-vs-memcmp.html
confused on strncmp vs memcmp
February 3, 2021 - I have two arrays defined as char a[4], b[4]....neither will (or should not) contain a null character. Can someone tell me is it better to use memcmp or strncmp when comparing the two? or for that matter do both work?
🌐
MathWorks
mathworks.com › matlab › language fundamentals › data types › characters and strings
strncmp - Compare first n characters of strings (case sensitive) - MATLAB
By convention, the zeroth character of a character vector or a string scalar is always '', a 0-by-0 character array. If n is less than 0, then strncmp treats it as 0. Data Types: double | single | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64
🌐
Reddit
reddit.com › r/embedded › is strcmp in embedded c safe? if not, what are the usual substitutes?
r/embedded on Reddit: Is strcmp in embedded C safe? If not, what are the usual substitutes?
February 3, 2023 -

I have an STM32756-EVAL board, and I would like to compare a uint8_t array to a char array.

uint8_t* inputCmd[5];
code_that_defines_the_inputCmd();
if (strcmp(inputCmd, "FIRMV") == 0){
	do_something();
    }
else{
	do_something_else();
}

Is strcmp in embedded C safe? If not, what are the usual substitutes?

🌐
TutorialsPoint
tutorialspoint.com › what-is-strncmp-function-in-c-language
What is strncmp() Function in C language?
March 19, 2021 - The C library function int strncmp(const char *str1, const char *str2, size_t n) compares at most the first n bytes of str1 and str2. An array of characters is called a string. Declar