1. 程式人生 > >atol(atoi)函式的實現要點

atol(atoi)函式的實現要點

以下是c標準庫中該函式的實現程式碼,從中分析要點
  1. /*** 
  2. *atox.c - atoi and atol conversion 
  3. * 
  4. * Copyright (c) 1989-1997, Microsoft Corporation. All rights reserved. 
  5. * 
  6. *Purpose: 
  7. * Converts a character string into an int or long. 
  8. * 
  9. *******************************************************************************/
  10. /*** 
  11. *long atol(char *nptr) - Convert string to long
     
  12. * 
  13. *Purpose: 
  14. * Converts ASCII string pointed to by nptr to binary. 
  15. * Overflow is not detected. 
  16. * 
  17. *Entry: 
  18. * nptr = ptr to string to convert 
  19. * 
  20. *Exit: 
  21. * return long int value of the string 
  22. * 
  23. *Exceptions: 
  24. * None - overflow is not detected. 
  25. * 
  26. *******************************************************************************/
  27. long __cdecl atol(  
  28.                   constchar *nptr  
  29.                   )  //1.const修飾
  30. {  
  31.     int c;          /* current char */
  32.     long total;     /* current total */
  33.     int sign;       /* if ''-'', then negative, otherwise positive */
  34.     /* skip whitespace */
  35. //char ,signed char 、unsigned char 型別的資料具有相同的特性然而當你把一個單位元組的數賦給一個整型數時,便會看到它們在符號擴充套件上的差異。
  36. //ascii碼當賦給整形數時要轉為unsigned char再轉為int
  37.     while ( isspace((int)(unsigned char)*nptr) )  //2.去掉首部的空格
  38.         ++nptr;  
  39.     c = (int)(unsigned char)*nptr++;  //取得第一個非空格的字元
  40.     sign = c; /* save sign indication */
  41.     if (c == '-' || c == '+')  //如果第一個非空格字元為符號
  42.         c = (int)(unsigned char)*nptr++; /* skip sign */  //跳過符號,將符號後的那個字元給c
  43.     total = 0;  //結果置為0
  44.     while (isdigit(c)) {  //3.如果碰到非法字元則停止
  45.         total = 10 * total + (c - '0'); /* accumulate digit */
  46.         c = (int)(unsigned char)*nptr++; /* get next char */
  47.     }  
  48.     if (sign == '-')  
  49.         return -total;  
  50.     else
  51.         return total; /* return result, negated if necessary */