Hi!
The following program gives the integer value of char string as output.Suppose if we give "1998",it will give integer 1998.In

i=i<<3+i<<1+(*string-'0')

I understood that it will multiply i by 10,but in *string-'0' I don't know what is going there..?.Here what refers string is it index in 1998 or whole 1998.
How this program works..?.What we are incrementing at string++ is it index.Please explain me I am a newbie...!
Any help would be highly appreciated.Thanxx

#include<stdio.h>

int myatoi(char *string);

int main(int argc, char* argv[])
{
printf("n%dn\n", myatoi("1998"));

return(0);
}

int myatoi(char *string)
{
int i;
i=0;
while(*string)
{
i=(i<<3) + (i<<1) + (*string-'0');
printf("%d\n",i);
string++;

// Dont increment i!

}
return(i);
}

I much perfer this instead of all those shifts. The code below could fail for integer overflow.

int myatoi(const char *string){
   int i = 0;
    // skip leading white space
   while( isspace(*string))
      ++string;
   while(*string && isdigit(*string))
   {
       i = (i * 10) + *string - '0';
       ++string;
   }
   return i;
}

I much perfer this instead of all those shifts. The code below could fail for integer overflow.

int myatoi(const char *string){
   int i = 0;
    // skip leading white space
   while( isspace(*string))
      ++string;
   while(*string && isdigit(*string))
   {
       i = (i * 10) + *string - '0';
       ++string;
   }
   return i;
}

In any way,what I haven't understood is

*string-'0'

.What string indicates whole string or index..
By the by what is "Post all questions in one of the boards." I didn't get you.I am from India now the time is 10:27 AM.

The asterisk before the variable means to reference only the first character in the string that the variable points to. So if string = "1234", then *string is looking at '1'. Another way to say the same thing is *string it the same as string[0].

Consequently, *string - '0' is the same as '1' - '0', which if you look at any ascii chart '1' = 49, and '0' = 48. So it boils down to 49 - 48 = 1.

The asterisk before the variable means to reference only the first character in the string that the variable points to. So if string = "1234", then *string is looking at '1'. Another way to say the same thing is *string it the same as string[0].

Consequently, *string - '0' is the same as '1' - '0', which if you look at any ascii chart '1' = 49, and '0' = 48. So it boils down to 49 - 48 = 1.

Very thanks...
I got this now...!
But some confusion in pointers .In many function we may not point and call them.What is the significance in this problem...
Thanks..

Sorry, I don't understand your question.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.