Search code examples
casciigetchar

getchar_unlocked() explanation


In this snippet, why is the condition checking whether ch<'0' || ch > '9' necessary.Why can't only the if statement suffice?

   #define getcx getchar_unlocked 
 inline void inp( int &n )
  n=0;
  char ch=getcx();
  int sign=1;

 while( ch < '0' || ch > '9' ) // Why is this while loop essential?
  {if(ch=='-')sign=-1; ch=getcx();}

  while(  ch >= '0' && ch <= '9' )
       n = (n<<3)+(n<<1) + ch-'0', ch=getcx();
  n=n*sign;
  }

Function returns 3454 as 3454 and -3454 as -3454


Solution

  • The idea behind the while loop is to skip over all non-digit characters on the way to the first digit, paying attention only to dashes. For example, this code would interpret

    hello-world123
    

    as -123

    A more likely scenario, though, is that the author of this code fragment wanted to skip over spaces. This kind of code is common in programming competitions, where programmers use the less safe getchar_unlocked in order to squeeze out a few microseconds while reading the input.

    It is needless to say that this is a very quick and dirty parser, intended for use with extremely clean data.