mahinirak 0 Newbie Poster

Hi guys,

I am coding the solution to K & R 2nd edition. I compare my solutions with the C answer book. Sometimes i feel my code is shorter but whether it is better and whether it confirms to good coding standards is what i am worried about. So i request the Top coders/Gurus/C Pundits here to kindly take a look at the code and give their valuable comments.

For starters here is my code for Ex 4-3 Pg 79( Extend the Polish calculator to include negative numbers)

My Code :

/* getop : get next operator or numeric operand */

int getop(char s[])
{
  int i,c ;

  while((s[0]=c=getch())==' ' || c =='\t')
    ;
  s[1]='\0';
  i=0;
  if (!isdigit(c) && c != '.')
    {
      if((c=='-')&&(isdigit(s[i+1]=c=getch()))) // if negative number
	{
	   i =i+1;
	}
      else
	return c; // not  a number
    }
 
  
  
      if(isdigit(c))  // collect integer part
	while(isdigit(s[++i]=c =getch()))
	  ;
    
  if (c=='.') // collect fraction part
    while (isdigit(s[++i]=c=getch()))
      ;
  s[i] = '\0';
  if(c !=EOF)
    ungetch(c);
  return NUMBER;
}

C Answer Book code

/* getop : get next operator or numeric operand */

int getop(char s[])
{
  int c,i ;

  while((s[0]=c=getch())==' ' || c =='\t')
    ;
  s[1]='\0';
  i=0;
  if (!isdigit(c) && c != '.'&& c != '-')
     	return c; // not  a number
  
   if(c=='-')
      if(isdigit(c=getch())|| c=='.')
           s[++i]=c; /*negative number */
      else {
             if(c != EOF)
                ungetch(c);
             return '-';
           }  
  
      if(isdigit(c))  // collect integer part
	while(isdigit(s[++i]=c =getch()))
	  ;
    
  if (c=='.') // collect fraction part
    while (isdigit(s[++i]=c=getch()))
      ;
  s[i] = '\0';
  if(c !=EOF)
    ungetch(c);
  return NUMBER;
}
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.