In C, the int and long data types are used to store integers, but their exact sizes and value ranges can vary across different systems and compilers. They are primarily categorized as 32-bit and 64-bit systems.
32-bit Systems:
-
int: In 32-bit systems,
intis typically defined as 32 bits (4 bytes), allowing it to store values from -2,147,483,648 to 2,147,483,647 (equivalent to -2^31 to 2^31 - 1). -
long: On many 32-bit systems,
longis also defined as 32 bits (4 bytes), so its value range is typically identical toint, i.e., from -2,147,483,648 to 2,147,483,647.
64-bit Systems:
-
int: On most 64-bit systems,
intremains 32 bits, so its value range is unchanged, still from -2,147,483,648 to 2,147,483,647. -
long: On 64-bit systems,
longis typically defined as 64 bits (8 bytes), enabling it to store values from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 (i.e., -2^63 to 2^63 - 1).
Important Note:
Notably, the C standard does not mandate that int and long must be 32-bit or 64-bit; their sizes depend on the specific system and compiler implementation. Therefore, to write portable code, include the <limits.h> header to determine the exact sizes and ranges of these types. For example, use the INT_MAX and INT_MIN macros to obtain the maximum and minimum possible values for int, and LONG_MAX and LONG_MIN for long.
Example Code:
c#include <stdio.h> #include <limits.h> int main() { printf("The range of int is from %d to %d.\n", INT_MIN, INT_MAX); printf("The range of long is from %ld to %ld.\n", LONG_MIN, LONG_MAX); return 0; }
This code outputs the value ranges for int and long types on the current system, aiding in understanding and correctly utilizing data type ranges during actual programming.