atol ~= atoi, labs

This commit is contained in:
K. Lange 2018-05-09 16:55:10 +09:00
parent 06c3574067
commit 643049ff32
4 changed files with 30 additions and 3 deletions

View File

@ -21,6 +21,8 @@ extern int setenv(const char *name, const char *value, int overwrite);
extern double atof(const char * nptr);
extern int atoi(const char * nptr);
extern long atol(const char * nptr);
extern long int labs(long int j);
#define EXIT_SUCCESS 0
#define EXIT_FAILURE 1

View File

@ -2,7 +2,7 @@
#include <stddef.h>
extern void * memset(void * dest, int c, size_t n);
extern void * memcpy(void * restrict dest, const void * restrict src, size_t n);
extern void * memcpy(void * dest, const void * src, size_t n);
extern void * memmove(void * dest, const void * src, size_t n);
extern void * memchr(const void * src, int c, size_t n);
@ -16,8 +16,8 @@ extern void * __attribute__ ((malloc)) valloc(uintptr_t size);
extern void free(void * ptr);
extern char * strdup(const char * s);
extern char * stpcpy(char * restrict d, const char * restrict s);
extern char * strcpy(char * restrict dest, const char * restrict src);
extern char * stpcpy(char * d, const char * s);
extern char * strcpy(char * dest, const char * src);
extern char * strchrnul(const char * s, int c);
extern char * strchr(const char * s, int c);
extern char * strrchr(const char * s, int c);

3
libc/stdlib/labs.c Normal file
View File

@ -0,0 +1,3 @@
long int labs(long int j) {
return (j < 0) ? -j : j;
}

View File

@ -343,6 +343,28 @@ static inline int isspace(int ch) {
return ch == ' ' || (unsigned int)ch-'\t' < 5;
}
long atol(const char * s) {
int n = 0;
int neg = 0;
while (isspace(*s)) {
s++;
}
switch (*s) {
case '-':
neg = 1;
/* Fallthrough is intentional here */
case '+':
s++;
}
while (isdigit(*s)) {
n = 10*n - (*s++ - '0');
}
/* The sign order may look incorrect here but this is correct as n is calculated
* as a negative number to avoid overflow on INT_MAX.
*/
return neg ? n : -n;
}
int atoi(const char * s) {
int n = 0;
int neg = 0;