Fog Creek Software
Discussion Board




Suggested atoi() function

What's wrong with this?

while ( *pStr && *pStr <= '9' && *pStr >= '0' )

...?

What's the "*pStr &&" for?  I assume the intent is to check for a null terminator.  That's not necessary.  A null is outside the range '0-9' so it would fail anyway.

while ( '0' <= *pStr && *pStr <= '9' )

...is sufficient.  I also rearranged it to be easier to read.

Just on principle I would avoid a construct like "if ( *pStr )".  It's a C language trick.  You have to know that strings are null terminated.  You have to know that a null has a numeric value of 0.  You have to know that numeric 0 is evaluated as false.  You have to know that any other number is evaluated as true.  It's obfuscated code.

"if ( *pStr != NULL )" is much better.  In that case you only have to know that strings are null terminated.  It's easier to port to other languages.

Let the compiler optimize the code!!!

William Frantz
Tuesday, July 23, 2002

I will not hire a person who strats coding without asking a VERY significant question:

What should the returned value be, if the argument string represents a number beyond the maximum representable integer?

Leo
Wednesday, July 24, 2002

*  Recent Topics

*  Fog Creek Home