Fog Creek Software
Discussion Board




comments on atoi() solution

If I were asked this question as framed in the solution, i.e. "write the definition for this function without using any built-in functions", the first thing I would have to ask the interviewer is precisely what they meant by "built-in functions" since this term does not (to me at least) have any precise meaning in the context of the C programming language (as opposed to awk, for example)

Having established that what they really meant was "standard C library functions and/or macros" I would then be able to proceed.

The "right to left" version of the solution is really somewhat perverse - I would only expect to see that offered if I explicitly asked for a "different" way of doing things from the more normal "left to right" approach.

Note also that the "right to left" approach gives different results from the "left to right" approach if non digits are present in the string. Indeed, if applied to the string "123A", the "right to left" approach returns 0, not 123.

The more conventional "left to right" solution can also be improved / simplified.

While it is a normal idiom when scanning a character string from left to right to first test whether the nul character at the end of  the string has been reached it is unnecessary in this case since we are about to apply a much stricter test (that the character lies between '0' and '9' inclusive) which renders the first test unnecessary.

i.e instead of writing:

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

you can write:

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

and get exactly the same results.

Finally I would expect a really knowledgeable C programmer to understand that what is being relied upon here is not the ASCII character set per-se, but rather the requirement in the C standard, that the characters in the execution character set that represent the digits 0 - 9 form a contiguous sequence with each successive character having a value 1 greater than it's predecessor (and *that* is why this is portable C code that is guaranteed to work on any conforming implementation regardless of whether the character set is ASCII, EBCDIC, Unicode or anything else).

Michael Davidson
Saturday, February 26, 2005

*  Recent Topics

*  Fog Creek Home