Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
401 views
in Technique[技术] by (71.8m points)

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.

question from:https://stackoverflow.com/questions/65643616/convert-one-character-in-a-c-array-to-uppercase-gives-c4244-warning

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...