C Program to find the Range of Fundamental Data Types

range of the data types

When you are working on data types then you should know the range of the data types. If you are not clear about the range then you might get the undefined behavior.

There is also two header file in c (limits.h and float.h) to provide the range but you can also create an own function to get the range of the data type.

But it is my advice don’t use your own function to get the range of the data types. I am writing this article because some student asks me to write a program to find the range of fundamental data types.

Steps to find the range of the data types

1. Calculate the size of the data type in bytes using the sizeof operator.
2. Convert the bytes into bits.
2. For signed data types, use formula -2^(n-1) to (2^(n-1))-1.
3. For unsigned data types, the range will be 0 to (2^n) – 1.

Where n is the number of bits of the data type.




See the below example program,

#include <stdio.h>

#define BITS(x) (sizeof(x) * 8 )


//Print Range of signed int
void SignedRange(unsigned int bits)
{
    int min = 0;
    int max = 0;

    min = - (1L <<(bits-1)); //Min value Equivalent to -2^(n-1)

    max =  ((1L <<(bits-1)) -1); //Max Value (2^(n-1)) -1

    printf("%d to %u\n\n",min,max);
}


//Print range of unsigned int
void UnsignedRange(unsigned int bits)
{
    unsigned int min = 0; //For unsigned min always 0
    unsigned long long  max = 0;

    max = ((1LLU << bits) - 1); //Equivalent to (2^n) -1

    printf(" %u to %llu\n\n", min, max);
}


int main()
{

    printf("\n  char Range => ");
    SignedRange(BITS(char));

    printf("\n  unsigned char Range =>");
    UnsignedRange(BITS(unsigned char));

    printf("\n  short Range => ");
    SignedRange(BITS(short));

    printf("\n  unsigned short Range => ");
    UnsignedRange(BITS(unsigned short));

    printf("\n  int Range => ");
    SignedRange(BITS(int));

    printf("\n  unsigned int Range => ");
    UnsignedRange(BITS(unsigned int));


    return 0;
}

Output:

C Program to find the Range of Fundamental Data Types

Recommended Articles for you:



Leave a Reply

Your email address will not be published. Required fields are marked *