atol(atoi)函式的實現要點
阿新 • • 發佈:2019-01-28
以下是c標準庫中該函式的實現程式碼,從中分析要點
- /***
- *atox.c - atoi and atol conversion
- *
- * Copyright (c) 1989-1997, Microsoft Corporation. All rights reserved.
- *
- *Purpose:
- * Converts a character string into an int or long.
- *
- *******************************************************************************/
- /***
- *long atol(char *nptr) - Convert string to long
- *
- *Purpose:
- * Converts ASCII string pointed to by nptr to binary.
- * Overflow is not detected.
- *
- *Entry:
- * nptr = ptr to string to convert
- *
- *Exit:
- * return long int value of the string
- *
- *Exceptions:
- * None - overflow is not detected.
- *
- *******************************************************************************/
- long __cdecl atol(
- constchar *nptr
- ) //1.const修飾
- {
- int c; /* current char */
- long total; /* current total */
- int sign; /* if ''-'', then negative, otherwise positive */
- /* skip whitespace */
- //char ,signed char 、unsigned char 型別的資料具有相同的特性然而當你把一個單位元組的數賦給一個整型數時,便會看到它們在符號擴充套件上的差異。
- //ascii碼當賦給整形數時要轉為unsigned char再轉為int
- while ( isspace((int)(unsigned char)*nptr) ) //2.去掉首部的空格
- ++nptr;
- c = (int)(unsigned char)*nptr++; //取得第一個非空格的字元
- sign = c; /* save sign indication */
- if (c == '-' || c == '+') //如果第一個非空格字元為符號
- c = (int)(unsigned char)*nptr++; /* skip sign */ //跳過符號,將符號後的那個字元給c
- total = 0; //結果置為0
- while (isdigit(c)) { //3.如果碰到非法字元則停止
- total = 10 * total + (c - '0'); /* accumulate digit */
- c = (int)(unsigned char)*nptr++; /* get next char */
- }
- if (sign == '-')
- return -total;
- else
- return total; /* return result, negated if necessary */
- }