ccompiler-warningstoupper

Convert one character in a C array to uppercase gives C4244 warning


Here is my code where I want to convert just ONE character in the string to uppercase.

TCHAR sPassword[16] = L"password";
INT iChar = toupper(sPassword[4]);
sPassword[4] = iChar;

It runs correctly, but I get a warning:

warning C4244: '=': conversion from 'int' to '_Ty', possible loss of data

I tried casting iChar with (INT) but it made no difference.


Solution

  • Warning is due to the narrowing of an INT object to a TCHAR one. Theses types exist to afford certainly fixability and may be the like range with other compilations settings.

    TCHAR iChar = (TCHAR) toupper(sPassword[4]); as answered by @Zsigmond Szabó is a good idea - when TCHAR is a char or friends.

    Yet there lies a deeper issue: toupper() is for single byte case conversion and is not the best conversion function to use when TCHAR is not char or the like.

    Code might have as well been:

    int iChar = toupper(sPassword[4]);  // if toupper must be used
    sPassword[4] = (TCHAR) iChar;
    

    To handle generally TCHAR case conversion, code needs more flexibility.


    TCHAR is not a standard C type nor definition.

    Assuming this is a MS TCHAR, consider _totupper().

    TCHAR iChar =  (TCHAR) _totupper(sPassword[4]);
    sPassword[4] = iChar;