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:
Recommended Articles for you:
- C program to find a neon number.
- Find the prime number using the C program.
- Find all prime numbers up to n using trial division and Sieve of Eratosthenes algorithm.
- Check date validity in C?
- How to use if in C programming.
- C language character set.
- How to use C if-else condition?
- How to use for loop in C?
- Elements of C Language.
- Data type in C language.
- Operators with Precedence and Associativity.
- 100 C interview Questions.
- Program to Count Number of Words in a Given String and File.
- 5 ways to find factorial of a number in C.
- C Program to find the Range of Fundamental Data Types.
- Fibonacci Series Program In C: A simple introduction.
- How to use atoi() and how to make own atoi()?
- Program to check leap year in C language.
- How to use the structure of function pointer in c language?
- Create a students management system in C.
- Create an employee management system in C.
- Top 11 Structure Padding Interview Questions in C
- File handling in C.