🌐
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.
🌐
BeginnersBook
beginnersbook.com › 2017 › 11 › c-strncmp-function
C strncmp() Function with example
#include <stdio.h> #include <string.h> int main () { char str1[20]; char str2[20]; int result; strcpy(str1, "hello"); strcpy(str2, "helLO WORLD"); //This will compare the first 4 characters result = strncmp(str1, str2, 4); if(result > 0) { printf("ASCII value of first unmatched character of ...
🌐
Cppreference
en.cppreference.com › w › c › string › byte › strncmp
strncmp - cppreference.com
#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!"
🌐
GeeksforGeeks
geeksforgeeks.org › c++ › stdstrncmp-in-c
std::strncmp() in C++ - GeeksforGeeks
July 2, 2024 - This function is a Standard Library function that is defined in <cstring> header file in C++. int strncmp(const char *str1, const char *str2, size_t count);
🌐
W3Schools
w3schools.com › c › ref_string_strncmp.php
C string strncmp() Function
C Examples C Real-Life Examples C Exercises C Quiz C Code Challenges C Compiler C Syllabus C Study Plan C Interview Q&A C Certificate ... char myStr1[] = "ABCD"; char myStr2[] = "ABCE"; int cmp = strncmp(myStr1, myStr2, 3); if (cmp > 0) { printf("%s ...
🌐
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.
🌐
W3Resource
w3resource.com › c-programming › string › c-strncmp.php
C strncmp() function
Following example demonstrates the strncmp() function by comparing only the first few characters of two strings. It uses the print_result function to output whether the strings are identical, less than, or greater than each other based on the ...
🌐
Tutorial Gateway
tutorialgateway.org › home › c programming › strncmp in c language
strncmp in C language
January 29, 2025 - #include <stdio.h> #include<string.h> int main() { char str1[50] = "abcdef"; char str2[50] = "abcd"; char str3[] = "ghi"; int i, j, k; i = strncmp(str1, str2, 4); printf("\n The Comparison of str1 and str2 Strings = %d", i); j = strncmp(str1, ...
Find elsewhere
🌐
TutorialsPoint
tutorialspoint.com › what-is-strncmp-function-in-c-language
What is strncmp() Function in C language?
Given below is a C program to compare ... "); gets(string1); printf("Enter String 2: "); gets(string2); //Comparing using library function// value = strncmp(string1,string2,4); //If conditions// if(value==0){ printf("%s is same as %s",string1,string2); } else if(value>0){ printf("%s ...
🌐
Aticleworld
aticleworld.com › home › how to use and implement own strncmp in c
How to use and Implement own strncmp in C - Aticleworld
August 23, 2020 - The strncmp function compares not more than n characters (characters that follow a null character are not compared) from the array pointed to by s1 to the array pointed to by s2. int strncmp(const char *s1, const char *s2, size_t n);
🌐
Javatpoint
javatpoint.com › strncmp-function-in-c
Strncmp() function in C - javatpoint
Strncmp() function in C with Tutorial, C language with programming examples for beginners and professionals covering concepts, c pointers, c structures, c union, c strings etc.
🌐
Microsoft Learn
learn.microsoft.com › en-us › cpp › c-runtime-library › reference › strncmp-wcsncmp-mbsncmp-mbsncmp-l
strncmp, wcsncmp, _mbsncmp, _mbsncmp_l | Microsoft Learn
Compare strings: The quick brown dog jumps over the lazy fox The QUICK brown fox jumps over the lazy dog Function: strncmp (first 10 characters only) Result: String 1 is greater than string 2 Function: strnicmp _strnicmp (first 10 characters ...
🌐
Wikibooks
en.wikibooks.org › wiki › C_Programming › string.h › strncmp
C Programming/string.h/strncmp - Wikibooks, open books for an open world
A simple implementation might be as follows: int strncmp (const char * const s1, const char * const s2, const size_t num) { const unsigned char * const us1 = (const unsigned char *) s1; const unsigned char * const us2 = (const unsigned char *) s2; for(size_t i = (size_t)0; i < num; ++i) { if(us1[i] ...
🌐
CS50
manual.cs50.io › 3 › strncmp
strncmp - CS50 Manual Pages
The strcmp() and strncmp() functions return an integer less than, equal to, or greater than zero if s1 (or the first n bytes thereof) is found, respectively, to be less than, to match, or be greater than s2. The program below can be used to demonstrate the operation of strcmp() (when given two arguments) and strncmp() (when given three arguments). First, some examples using strcmp(): $ ./string_comp ABC ABC <str1> and <str2> are equal $ ./string_comp ABC AB # 'C' is ASCII 67; 'C' - '\0' = 67 <str1> is greater than <str2> (67) $ ./string_comp ABA ABZ # 'A' is ASCII 65; 'Z' is ASCII 90 <str1> is
🌐
OpenGenus
iq.opengenus.org › strncmp-in-c
strncmp in C
November 6, 2019 - Consider this example where both ... 'n', 'g', 'e', 'n', 'u', 's'}; char data2[] = {'o', 'p', 'e', 'n', 'g', 'e', 'n', 'u', 's'}; printf("%d", strncmp(data1, data2, 20)); return 0; }...
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.

🌐
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?