Facebook Page Twitter Page LinkedIn Page
× C++ Standard Library C++ STL Library


The C++ <cwchar> wcscmp() function is used to compare two null-terminated wide strings lexicographically. The function starts comparing the first pair of wide characters of each wide string and continues comparing until the pair of wide characters are different or until a terminating null wide character is reached.

Syntax

int wcscmp (const wchar_t* lhs, const wchar_t* rhs);          

Parameters

lhs Specify pointer to the first null-terminated wide string to compare.
rhs Specify pointer to the second null-terminated wide string to compare.

Return Value

Based on the value of lhs and rhs, the function returns the following:

  • Negative value if lhs appears before rhs in lexicographical order.
  • Zero if lhs and rhs compare equal.
  • Positive value if lhs appears after rhs in lexicographical order.

Example: Value returned by function = 0

The below example shows the usage of wcscmp() function.

#include <iostream>
#include <cwchar>
using namespace std;
 
int main (){
  wchar_t str1[20] = L"Hello";
  wchar_t str2[20] = L"Hello";
  
  //comparing str1 and str2
  int retval = wcscmp(str1, str2);

  //displaying the result
  if(retval != 0)
    cout<<"str1 and str2 are not equal.\n";
  else
    cout<<"str1 and str2 are equal.\n";
 
  cout<<"Value returned by the function: "<<retval<<"\n";

  return 0;
}

The output of the above code will be:

str1 and str2 are equal.
Value returned by the function: 0

Example: Value returned by function < 0

Lets consider this example where the returned value is less than zero.

#include <iostream>
#include <cwchar>
using namespace std;
 
int main (){
  wchar_t str1[20] = L"Hello";
  wchar_t str2[20] = L"World";
  
  //comparing str1 and str2
  int retval = wcscmp(str1, str2);

  //displaying the result
  if(retval != 0)
    cout<<"str1 and str2 are not equal.\n";
  else
    cout<<"str1 and str2 are equal.\n";

  cout<<"Value returned by the function: "<<retval<<"\n";

  return 0;
}

The output of the above code will be:

str1 and str2 are not equal.
Value returned by the function: -1

Example: Value returned by function > 0

Lets consider another example where the returned value is greater than zero.

#include <iostream>
#include <cwchar>
using namespace std;
 
int main (){
  wchar_t str1[20] = L"Hello";
  wchar_t str2[20] = L"Apple";
  
  //comparing str1 and str2
  int retval = wcscmp(str1, str2);

  //displaying the result
  if(retval != 0)
    cout<<"str1 and str2 are not equal.\n";
  else
    cout<<"str1 and str2 are equal.\n";

  cout<<"Value returned by the function: "<<retval<<"\n";

  return 0;
}

The output of the above code will be:

str1 and str2 are not equal.
Value returned by the function: 1

❮ C++ <cwchar> Library