1

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.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
JeffR
  • 765
  • 2
  • 8
  • 23

2 Answers2

5

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;
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
2

You are getting a warning because TCHAR is a char (1 byte) and iChar is an int (most likely 4 bytes). In order to assign an integer to a char, it has to truncate that int in order to fit in the char, which obviously loses 3 bytes worth of data. You can get rid of the error by explicitly casting iChar to a TCHAR, like this:

sPassword[4] = (TCHAR) iChar;

Or, you can declare iChar as a TCHAR, and do the conversion when you assign it, like this:

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