Mar
Mar

Reputation: 951

Be careful: the "unsigned" specifier changes the size of the wchar_t type in Visual Studio

Adding the unsigned specifier to the wchar_t type in Visual Studio changes the type size from 2 to 4 bytes.

By running the following two lines of code in Visual Studio 2008, or in the latest Visual Studio 2019:

    cout << "wchar_t: " << sizeof(wchar_t) << endl;
    cout << "unsigned wchar_t: " << sizeof(unsigned wchar_t) << endl;

You get 2 for wchar_t and 4 for unsigned wchar_t and just the warning C4076 ('unsigned': cannot be used with type 'wchar_t').

The expected behavior was leaving the 2 bytes size. The documentation says nothing on size changing but tells just to use a compiler option to make the whcar_t a typedef for unsigned short:

Microsoft-specific: By default, wchar_t is a native type, but you can use /Zc:wchar_t- to make wchar_t a typedef for unsigned short. The __wchar_t type is a Microsoft-specific synonym for the native wchar_t type.

This is, probably, another reason for enabling the "Treat Warnings as Errors" compiler option and follow the zero warnings rule.

At least for new projects. Unfortunately, it may be from hard to impossible to follow this rule when working with a legacy code.

Upvotes: 0

Views: 173

Answers (1)

Alan Birtles
Alan Birtles

Reputation: 36399

I think visual studio is correct here, there is no provision in the standard for unsigned wchar_t (or signed wchar_t) so it is up to compilers how they handle it. Whilst an error would be nice (as raised by GCC and Clang) a warning is OK too.

Presumably the 4 bytes is because Visual Studio has to decide to discard one of unsigned or wchar_t and decides to discard wchar_t leaving you with an unsigned int.

Upvotes: 2

Related Questions