以下是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(
- const char *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 */
- }