Reputation: 4523
In Visual Studio why would one compare the value of a character (previously a char, now a wchar_t) to the value of -1?
I have a project with multiple invalid checks against -1:
TCHAR ch;
...
if(ch==-1)
Coverity is telling me that ""ch == -1" is always false regardless of the values of its operands."
Now, this was originally written to use char values instead of wchar_t, and was upgraded when unicode support was needed. I need to figure out why the "char ch;" was being checked against -1 so that I can make a similar check against the wchar_t.
Upvotes: 0
Views: 467
Reputation: 47448
The integer constant EOF
is typically #defined to -1
. If that is inded what your code is checking (depends on where ch
came from), then the corresponding wchar_t
comparison would be to WEOF
, and the appropriate Windows TCHAR macro seems to be _TEOF.
PS: As absolutely correctly pointed out in comments, if a value was converted to char
or to wchar_t
, it is too late to compare it to EOF
or WEOF
: plenty of encodings use the char '\xff'
as a valid letter, and that becomes indistinguishable from EOF after such conversion. The code is simply wrong: the variable ch
needs to have type int
/wint_t
/_TINT
for any such comparison to be valid.
Upvotes: 1
Reputation: 153967
What is the type of TCHAR
? If it is an unsigned type really
smaller than int
, the expression can never be be true, since
integral promotion will occur, resulting in a large positive
integer, but still something less than UINT_MAX
, where as -1
is UINT_MAX
. (If TCHAR
is something like unsigned short
,
for example, it can typically have values in the range
0...65365, which will convert to an int
or an unsigned int
without changing the value. -1, on the other hand, will
typically convert to something like 4294967295 when converted to
unsigned.)
If you're checking for end of file (e.g. after an
std::iwstream.get()
), then you should do so before
converting the results from int
. Even with char
, it doesn't
work; if plain char
is unsigned, then it can never be -1, and
if it is signed, then one valid character (ÿ
in ISO 8859-1)
will appear to be end of file.
Upvotes: 0