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,

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | #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; } |