C++ strncmp() function with example

The strncmp() function in C++ is used for comparing two string and checking if they are equal or not. strcmp() function compares two strings character by character from the first character until the end of one of the string occurs then it returns the result.

Basic Syntax

int strncmp ( const char * str1, const char * str2, size_t num );

And the parameters are:

Parameter Description
str1 This is first string that should be comapared.
str2 This is second string that should be comapared.
num This is maximum number of characters of string to be compared.

Return Value

This function returns the following values:

  • 0 : If both strings are equal means all characters in the string are same then it will return 0.
  • Greater than zero (Positive Integer) : It returns a value greater than zero when the ASCII value of the first unmatched character in str1 is greater than second.
  • Less than zero (Negative) : It returns value less than zero when ASCII value of the first unmatched character in str2 is less than second.


Following is the example for C++ strncmp() function.

// C++ program for illustration of function strncmp
#include <stdio.h>
#include <string.h>

int main()
    char string1[] = "Programming";
    char string2[] = "PROGRAMMING"; 
    char string3[] = "programming";
    char string4[] = "Programming";
    int result;

    result = strcmp(string1, string2);
    printf("comparing string1 to string2 = %d\n", result);
    result = strcmp(string1, string3);
    printf("comparing string1 to string3 = %d\n", result);
    result = strcmp(string1, string4);
    printf("comparing string1 to string4 = %d\n", result);

    return 0;

The output should be:

comparing string1 to string2 = 32
comparing string1 to string3 = -32
comparing string1 to string4 = 0