What is wcscmp in C?

The wcscmp function in C lexicographically compares two wide strings. The function sequentially compares the elements of both strings until it encounters a mismatch.

The process is illustrated below:

Note: A wide string is comprised of characters from the Unicode character set.

To use the wcscmp function, you will need to include the <wchar.h> library in the program, as shown below:

#include <wchar.h>

The prototype of the wcscmp function is shown below:

int wcscmp(const wchar_t *s1, const wchar_t *s2);

Parameters

The wcscmp function takes two null-terminated wide strings as parameters.

Return value

The wcscmp function compares the provided strings and returns one of the following:

  • 00 if the two strings are equal.
  • A positive integer if s1 is lexicographically greater than s2.
  • A negative integer if s1 is lexicographically less than s2.

The behavior of the wcscmp function is undefined if either s1 or s2 do not point to null-terminated wide strings.

Example

The code below shows how the wcscmp function works in C:

#include <stdio.h>
#include <wchar.h>
int main() {
// initializing strings
wchar_t str[] = L"Case";
wchar_t arr[3][5] = {L"Case", L"Cave", L"Care"};
// iterating over strings
for(int i = 0; i < 3; i++)
{
// comparing strings
int result = wcscmp(str, arr[i]);
// displaying result
if(result == 0)
{
printf("\'%ls\' and \'%ls\' are equal.\n", str, arr[i]);
}
else if(result < 0)
{
printf("\'%ls\' is less than \'%ls\'.\n", str, arr[i]);
}
else
{
printf("\'%ls\' is greater than \'%ls\'.\n", str, arr[i]);
}
}
return 0;
}

Explanation

First, the code initializes a 2D-Array of wide strings. Each of the strings in this array is meant to be compared with the wide string str. The ‘L’ identifier in lines 7 and 8 informs the compiler that the Unicode character set is being used.

The for-loop in line 11 iterates over each element in the array. The wcscmp function in line 14 proceeds to compare the wide string stored in str with the extracted array element, and the result is printed accordingly.

The first comparison involves the same string, “Case,” being served as both parameters to the wcscmp function. Therefore, the result of this comparison is 00.

During the second iteration of the loop, a comparison occurs between the strings “Case” and “Cave.” There is a mismatch at the third character of both of these strings, and since ‘s’ appears before ‘v’ in the alphabet, wcscmp returns a negative integer.

Similarly, in the final comparison between “Case” and “Care,” the mismatch again occurs at the third character. However, since ‘s’ appears after ‘r’ in the alphabet, a positive integer is returned by wcscmp.

Copyright ©2024 Educative, Inc. All rights reserved