# Calculate range of data types using C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

In C++ we have different datatypes like int, char, double etc. In this section we will see how to get the size of them programmatically.

We can get the size of datatypes in byte, so we can simply multiply them into 8 to get the values in bits. Now we know that if the number of bits are n, then the minimum range will be – 2^(n-1), and maximum range will be 2^(n-1) – 1 for signed numbers. For unsigned numbers it will be 2^n – 1 as there are no negative numbers.

## Example Code

#include <iostream>
#include <cmath>
#define SIZE(x) sizeof(x) * 8 //Get the size in bits
using namespace std;
void getRange(string type, int n) {
if(type.compare("SIGNED") == 0) { //for signed numbers calculate lower and upper limit
int min = pow(2, n - 1);
int max = pow(2, n - 1) - 1;
cout << "Range from " << (-1) * min << " to " << max <<endl;
}else{ //for signed numbers calculate limit from 0
int range = pow(2, n )-1;
cout << "Range from 0 to " << range << endl;
}
}
int main() {
cout << "For Signed int: ";
getRange("SIGNED", SIZE(int));
cout << "For Signed float: ";
getRange("SIGNED", SIZE(float));
cout << "For Unsigned int: ";
getRange("UNSIGNED", SIZE(unsigned int));
cout << "For Unsigned short: ";
getRange("UNSIGNED", SIZE(unsigned short int));
cout << "For Signed char: ";
getRange("SIGNED", SIZE(char));
}

## Output

For Signed int: Range from -2147483648 to 2147483647
For Signed float: Range from -2147483648 to 2147483647
For Unsigned int: Range from 0 to -2147483648
For Unsigned short: Range from 0 to 65535
For Signed char: Range from -128 to 127