Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

This is how the strtol function in the standard C library works. Here's a test program:

    #include <stdio.h>
    #include <stdlib.h> /* strtol, strtod */

    /* Convert string to long and return true if successful. */
    int string_long(char *beg, long *num)
        {
        char *end;
        *num = strtol(beg, &end, 10);
        return *beg != '\0' && *end == '\0';
        }

    int main(void)
        {
        char *x_str = "9223372036854775807";
        char *y_str = "9223372036854775808";

        long x;
        long y;

        int x_ok = string_long(x_str, &x);
        int y_ok = string_long(y_str, &y);

        printf("x_str = %s\n", x_str);
        printf("y_str = %s\n", y_str);

        printf("x = %ld (ok=%d)\n", x, x_ok);
        printf("y = %ld (ok=%d)\n", y, y_ok);
        printf("x and y are %s\n", x == y ? "equal" : "not equal");

        return 0;
        }

And here's the output:

    x_str = 9223372036854775807
    y_str = 9223372036854775808
    x = 9223372036854775807 (ok=1)
    y = 9223372036854775807 (ok=1)
    x and y are equal
I compiled it like so:

    gcc -c -Wall -Werror -ansi -O3 -fPIC src/test_num.c -o obj/test_num.o


Incidentally if you try using those numeric constants directly in a C program, it fails to compile:

    #include <stdio.h>

    int main(void)
        {
        long x = 9223372036854775807;
        long y = 9223372036854775808;

        printf("x = %ld\n", x);
        printf("y = %ld\n", y);
        printf("x and y are %s\n", x == y ? "equal" : "not equal");

        return 0;
        }
The error message is:

    gcc -c -Wall -Werror -ansi -O3 -fPIC src/test_num2.c -o obj/test_num2.o
    src/test_num2.c: In function ‘main’:
    src/test_num2.c:6:11: error: integer constant is so large that it is unsigned [-Werror]
    src/test_num2.c:6:2: error: this decimal constant is unsigned only in ISO C90 [-Werror]
    cc1: all warnings being treated as errors




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: