C library - atol() function

The C stdlib library atol() function is used to convert a string passed as argument into a long integer number. For example. if we have string "123" and we want to convert it into long integer 123, you would use atol("123").

This function starts by skipping any leading white-space characters and then processes the subsequent characters as part of the number. If the string starts with a "+" or "-" sign, considered as number. The conversion stops when an invalid string found.


Following is the C library syntax of the atol() function −

long int atol(const char *str)


This function accepts a single parameter −

  • str − It is a pointer to a null-terminated sting, which represent the a long integer.

Return Value

This function returns a long integral number, represents long value. If the input string is not a valid string's number, it returns 0.

Example 1

Following is the basic c program to convert the string value into the long integer value using the atol() function.

#include <stdlib.h>
#include <stdio.h>
int main(void)
   long int val;
   char *str; 
   str = "20152030";
   //convert string into long int
   val = atol(str); 
   printf("Long int value = %ld", val);


Following is the output −

Long int value = 20152030

Example 2

Let's see another c program, we concatenated two string and then convert the resulting string into a long integral number using the atol() function.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {	
   // Define two strings to concatenate
   char str1[] = "24";
   char str2[] = "2024";
   //calculate the length of string first + second
   int length = strlen(str1) + strlen(str2) + 1;

   // Allocate memory for the concatenated string
   char *concatenated = malloc(length);

   // check memory allocation if null return 1.
   if(concatenated == NULL) {
      printf("Memory allocation failed\n");
      return 1;

   // Concatenate str1 and str2
   strcpy(concatenated, str1);
   strcat(concatenated, str2);

   // Convert concatenated string into a long int.
   // use the atol() function
   long int number = atol(concatenated);

   printf("The concatenated string is: %s\n", concatenated);
   printf("The long int value is: %ld\n", number);

   // at the last free the alocated memory
   return 0;


Following is the output −

The concatenated string is: 242024
The long int value is: 242024

Example 3

Below c program convert the character string into the long integral number.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main () {
   long int res;
   char str[20];
   //define a string
   strcpy(str, "tutorialspointIndia");
   //use atoi() function
   res = atol(str);
   printf("String Value = %s\n", str);
   printf("Integral Number = %ld\n", res);


Following is the output −

String Value = tutorialspointIndia
Integral Number = 0