C long Data Type
In C, the long data type is an extended version of int that allows storing larger integer values. It is useful when working with numbers that exceed the range of int. The long type supports both positive and negative whole numbers.
1 Storage Size of long Data Type
The storage size of long depends on the system and compiler. Typically:
- On most 32-bit systems:
longis 4 bytes (32 bits). - On most 64-bit systems (Linux/macOS – LP64 model):
longis 8 bytes (64 bits). - On Windows (LLP64 model):
longis still 4 bytes, even on 64-bit systems.
2 Values Stored by long Data Type
The long data type is used to store large whole numbers, including both positive and negative values.
Example values that can be stored in long:
100000, -500000, 2147483647, -2147483648
3 Example: Declaring and Using long Variables
Let’s see a simple program demonstrating how to declare and use long variables in C.
main.c
#include <stdio.h>
int main() {
long num1 = 50000;
long num2 = -200000;
long sum = num1 + num2;
printf("Number 1: %ld\n", num1);
printf("Number 2: %ld\n", num2);
printf("Sum: %ld\n", sum);
return 0;
}
Explanation:
- We declare three
longvariables:num1,num2, andsum. - We assign values 50000 and -200000 to
num1andnum2respectively. - The sum of these two numbers is stored in the
sumvariable. - We print the values using
printf()with the format specifier%ld.
Output:
Number 1: 50000
Number 2: -200000
Sum: -150000
4 Checking Storage Size of long Programmatically
We can determine the storage size of long in bytes using the sizeof operator.
main.c
#include <stdio.h>
int main() {
printf("Size of long: %lu bytes\n", sizeof(long));
return 0;
}
Output (varies based on system architecture):
Size of long: 8 bytes
5 Minimum and Maximum Values of long
The range of values a long can store depends on its size:
| Storage Size | Minimum Value | Maximum Value |
|---|---|---|
| 4 bytes | -2,147,483,648 | 2,147,483,647 |
| 8 bytes | -9,223,372,036,854,775,808 | 9,223,372,036,854,775,807 |
6 Getting Maximum and Minimum Values of long Programmatically
The maximum and minimum values of a long can be retrieved using limits.h.
main.c
#include <stdio.h>
#include <limits.h>
int main() {
printf("Minimum long value: %ld\n", LONG_MIN);
printf("Maximum long value: %ld\n", LONG_MAX);
return 0;
}
Output:
Minimum long value: -9223372036854775808
Maximum long value: 9223372036854775807
Conclusion
In this tutorial, we explored the long data type in C, including:
- Its ability to store larger whole numbers (both positive and negative).
- Its typical storage size of 4 or 8 bytes, depending on the system.
- How to get the storage size programmatically using
sizeof(). - The minimum and maximum values that
longcan store. - How to retrieve these values using
limits.h.
