Should this char be unsigned?
I found some confusing code during code review and am a bit puzzled. Doing some research I found this situation. I wrote this sample of code to highlight the problem
char d = '©';// this is -87,the copyright symbol , (actually its 169 unsigned)
if(ispunct(d)) // will assert.
{
}
so, the programmer who was bug fixing, did the following:
char d = '©';// this is -87,the copyright symbol , (actually its 169 unsigned)
if(ispunct((unsigned char)d)) // will not assert, because it will be 169.
{
}
My question is whether it is OK to make the char
unsigned ? Ideally, I wouldn't use char
but u开发者_如何学编程se a Unicode char to avoid this kinds of problem, but the software is very old and wont be reengineered any time soon.
I am using Visual Studio 2008. ispunct()
can be found in ctype.h
.
The cast is correct in this case. From man ispunct
:
The
ispunct()
function tests for any printing character except for space (' '
) or a character for whichisalnum(3)
istrue
. The value of the argument must be representable as anunsigned char
or the value ofEOF
.
If you want to use ispunct
, then there's no way around it.
_ASSERTE((unsigned)(c + 1) <= 256);
That's what caused the assertion to fail and hence the cast is appropriate.
It's perfectly legitimate to do the cast. I believe in C variables are signed by default but the cast makes it useable.
精彩评论