Range of int in C
0 379
In C programming, the int data type represents integer values and its size, and range can vary depending on the architecture and compiler implementation.
Typically, an int takes 4 bytes (32 bits) of memory on most modern systems.
The range of int can be determined using the limits provided by the
For a standard 32-bit int:
Minimum Value: -2,147,483,648
Maximum Value: 2,147,483,647
It's crucial to be aware of these limits to prevent overflow (when a value exceeds the maximum limit) and underflow (when a value goes below the minimum limit) while performing arithmetic operations.
Example:
// Print Minimum and Maximum Values of int: #include<stdio.h>#include<limits.h> int main() { printf("Minimum value of int: %d\n", INT_MIN); printf("Maximum value of int: %d\n", INT_MAX); return 0; }
Output:
Minimum value of int: -2147483648 Maximum value of int: 2147483647
Check Overflow in int:
// Program to Check Overflow in int #include<stdio.h>#include<limits.h> int main() { int num = INT_MAX; printf("Initial value: %d\n", num); // Add 1 to check overflow num = num + 1; printf("After adding 1: %d\n", num); return 0; }
Output:
Initial value: 2147483647 After adding 1: -2147483648
Check Underflow in int:
// Program to Check Underflow in int #include<stdio.h>#include<limits.h> int main() { int num = INT_MIN; printf("Initial value: %d\n", num); // Subtract 1 to check underflow num = num - 1; printf("After subtracting 1: %d\n", num); return 0; }
Output:
Initial value: -2147483648 After subtracting 1: 2147483647
The
Overflow and underflow can lead to undefined behavior, so always check the range limits before performing arithmetic operations on int values.
For platforms with different architectures or compilers, the size and range of int might vary.
Always use sizeof(int) and
These programs demonstrate how to determine and utilize the range of the int data type in C, highlighting its minimum and maximum values and showcasing potential overflow and underflow scenarios.
Share:
Comments
Waiting for your comments