Search code examples
c++11unicodeintunicode-stringwidechar

C++ 11: Adding an int to a wchar_t


I naively added an int to a wchar_t resulting in a Visual Studio 2013 warning.

L'A' + 1 // next letter

warning C4244: 'argument' : conversion from 'int' to 'wchar_t', possible loss of data

So the error is concerned that a 4 byte int is being implicitly cast to a 2 byte wchar_t. Fair enough.

What is the C++ 11 standards safe way of doing this? I'm wondering about cross-platform implications, code-point correctness and readability of doing things like: L'A' + (wchar_t)1 or L'A' + \U1 or whatever. What are my coding options?

Edit T+2: I presented this question to a hacker's group. Unsurprisingly, no one got it correct. Everyone agreed this is a great interview question when hiring C/C++ Unicode programmers because it's very terse and deserves a meaty conversation.


Solution

  • Until I see a more elegant answer, which I hope there is, I'll go with this pattern:

    (wchar_t)(L'A' + i)
    

    I like this pattern because i can be negative or positive and it will evaluate as expected. My original notion to use L'A' + (wchar_t)i is flawed if i is negative and wchar_t is unsigned. I'm assuming here that wchar_t is implementation dependent and could be signed.