non-sense assertion in VC7.1

G

Guest

Try to compiler and run the following code in DEBUG mode, an assertion dialog
will be popped. Can I ignore this assertion dialog and why does this code
cause to an assertion?

--
int _tmain(int argc, _TCHAR* argv[])
{
char c = -3;
if(isdigit(c))
{
puts("Character '-3' is a digit");
}
else
{
puts("Character '-3' is not a digit");
}
return 0;
}
 
D

Doug Harrison [MVP]

Try to compiler and run the following code in DEBUG mode, an assertion dialog
will be popped. Can I ignore this assertion dialog and why does this code
cause to an assertion?

--
int _tmain(int argc, _TCHAR* argv[])
{
char c = -3;
if(isdigit(c))
{
puts("Character '-3' is a digit");
}
else
{
puts("Character '-3' is not a digit");
}
return 0;
}

The <ctype.h> functions take ints and are defined only on those values of
int that are representable in unsigned char, plus EOF. In VC++ and most
other compilers, plain char is signed, and it's undefined to pass char(-3)
to functions like isdigit, because it gets promoted to int(-3). The
solution is to cast to unsigned char, e.g.

if (isdigit((unsigned char) c)) ...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top