"
JS" <sfsdfs@asdas.com> wrote in message
news:d14m9k$gmd$1@news.net.uni-c.dk...[color=blue]
> #include <ctype.h>
> double atof(char s[]){
>
> double val, power;
> int i, sign;
>
> for (i = 0; isspace(s[i]); i++)
> ;
> sign = (s[i] == '-') ? -1 : 1;
> if (s[i] == '+' || s[i] == '-')
> i++;
>
> for (val = 0.0; isdigit(s[i]); i++)
> val = 10.0 * val + (s[i] - '0');
>
> if (s[i] == '.')
> i++;
>
> for (power = 1.0; isdigit(s[i]); i++){
> val = 10.0 * val + (s[i] - '0');
> power *= 10.0;
> }
> return sign * val / power;
> }
>
>
>
> The first for loop never terminates and I guess nothing is executed in its
> body.
>[/color]
That loop moves the starting point of the parsing code up past any leading
spaces. There is not protection there if the array passed contains only
spaces and no null terminator at the end, so I assume it's a requirement
that the function be provided a valid null-terminated string. If it never
terminates, then you've given it invalid data.
[color=blue]
> How should (s[i] - '0') be understood? Have never seen a char subtracted
> from another char before.[/color]
That's a common method if getting the values 0 through 9 from the characters
'0' through '9'. It only works if your character set contains the
characters '0' through '9' in order (which they all do, from everything I've
seen, but I don't know if it's a requirement). If you subtract '0' from '0,
you get 0. If you subtract '0' from '3', you get 3. Etc.
The code is taking a string containing a representation of a floating-point
number, and converting into an actual float value.
-Howard