C
Christopher Benson-Manica
I just ran across this code (assume that buf is valid and large
enough to hold all characters printed to it):
const char *foo( double d, char *buf )
{
char *cp;
if( d == (int)d ) { /* 1 */
sprintf( buf, "%d", (int)d ); /* 2 */
}
else { /* 3 */
sprintf( buf, "%.3lf", d );
cp=buf+strlen( buf );
while( cp > buf && cp[-1] == '0' ) {
*(--cp)=0;
}
if( cp > buf && cp[-1] == '.' ) {
cp[-1]=0;
}
}
return buf;
}
1. Obviously this cast is unsafe - is it unsafe even if 0 < d < INT_MAX?
The code wants to verify that d has no decimal part, apparently.
Is floor(d) == ceil(d) an acceptable alternative? Will it work?
2. Presumably this line should be
printf( buf, "%.0lf", d );
Is that correct?
3. As near as I can make out, this attempts to ensure that there are
no trailing 0's printed, and that there is not a bare decimal
point either. Is there a better way to do that?
enough to hold all characters printed to it):
const char *foo( double d, char *buf )
{
char *cp;
if( d == (int)d ) { /* 1 */
sprintf( buf, "%d", (int)d ); /* 2 */
}
else { /* 3 */
sprintf( buf, "%.3lf", d );
cp=buf+strlen( buf );
while( cp > buf && cp[-1] == '0' ) {
*(--cp)=0;
}
if( cp > buf && cp[-1] == '.' ) {
cp[-1]=0;
}
}
return buf;
}
1. Obviously this cast is unsafe - is it unsafe even if 0 < d < INT_MAX?
The code wants to verify that d has no decimal part, apparently.
Is floor(d) == ceil(d) an acceptable alternative? Will it work?
2. Presumably this line should be
printf( buf, "%.0lf", d );
Is that correct?
3. As near as I can make out, this attempts to ensure that there are
no trailing 0's printed, and that there is not a bare decimal
point either. Is there a better way to do that?