C++ mblen()

The mblen() function in C++ determines the size (in bytes) of a multibyte character.

The mblen() function is defined in <cstdlib> header file.

mblen() prototype [As of C++ 11 standard]

int mblen (const char* s, size_t max);

The mblen() function takes a two arguments s and max, and returns a integer value. The pointer s points to the first byte of a multibyte character whose size is returned by the function.


mblen() Parameters

  • s: Pointer to the first byte of a multibyte character or a null pointer.
  • max: Maximum number of bytes in s that can be examined.

mblen() Return value

If s is a null pointer, a call to mblen() resets its internal conversion state to represent the initial shift state and returns:

  • 0 if the current multibyte encoding is not state-dependent (does not use shift sequences).
  • non-zero value if the current multibyte encoding is state-dependent (uses shift sequences).

If s is not a null pointer, the mblen() function returns:

  • the number of bytes that are contained in the multibyte character.
  • -1 if the first bytes pointed to by s do not form a valid multibyte character.
  • 0 if s is pointing at the null character '\0'.

Example: How mblen() function works in C++?

#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;

int main()
{
	int len;
	char *s = (char *)malloc(20);
	strcpy(s,"\xe4\xbd\xa0\xe5\xa5\xbd");

	/* resets the conversion state */
	mblen(NULL, 0);
	len = mblen(s,strlen(s));

	cout << "Length of multibyte character: " << len << endl;
	return 0;
}

When you run the program, the output will be:

Length of multibyte character: 1
Did you find this article helpful?