non-sense assertion in VC7.1

  • Thread starter Thread starter Guest
  • Start date Start date
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;
}
 
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)) ...
 
Back
Top