w3resource

C atol() function

C atol() function - Convert a string to a long integer

The atol() function is used to convert a character string to a long value.

Syntax:

long int atol(const char *str)

Parameters:

Name Description Required /Optional
str String to be converted. Required

Return value from atol()

  • Returns a long value.

Example: atol() function

The following example shows the usage of atol() function.


#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
 
int main(void)
{   
    char    *str = NULL;
    long    value = 0;
    // string value with leading and trailing white spaces.
    str = "  -7435 ";
    value = atol( str );
    printf( "Function: atol( \"%s\" ) = %d\n", str, value );

    // string value with an arbitrary decimal point.
    str = "732946.45";
    value = atol( str );
    printf( "Function: atol( \"%s\" ) = %d\n", str, value );

    // Another example with an overflow condition occurring.
    str = "234243820342342-422348";
    value = atol( str );
    printf( "Function: atol( \"%s\" ) = %d\n", str, value );
    if (errno == ERANGE)
    {
       printf("Overflow condition occurred.\n");
    }
}

Output:

Function: atol( "  -7435 " ) = -7435
Function: atol( "732946.45" ) = 732946
Function: atol( "234243820342342-422348" ) = 598985798

C Programming Code Editor:

Previous C Programming: C atoi()
Next C Programming: C strtod()



Follow us on Facebook and Twitter for latest update.

C Programming: Tips of the Day

What's the point of const pointers?

const is a tool which you should use in pursuit of a very important C++ concept:

Find bugs at compile-time, rather than run-time, by getting the compiler to enforce what you mean.

Even though it does not change the functionality, adding const generates a compiler error when you're doing things you didn't mean to do. Imagine the following typo:

void foo(int* ptr)
{
    ptr = 0;// oops, I meant *ptr = 0
}

If you use int* const, this would generate a compiler error because you're changing the value to ptr. Adding restrictions via syntax is a good thing in general. Just don't take it too far -- the example you gave is a case where most people don't bother using const.

Ref : https://bit.ly/33Cdn3Q