Range of int in C
×


Range of int in C

36

 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 header file.

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 header file provides macros to get the minimum and maximum values of different data types in C.

 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 to get accurate information.

 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.



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments