Calculate Range of Data Types Using C++



Here, we are going to learn how we can calculate the range of the different C++ data types such as signed data types (int, char, float, etc.) and unsigned data types (unsigned char, unsigned int, unsigned float, etc.).

Calculating Range of Signed Data Types

In C++, signed data types are used to represent both positive and negative integer values. So, to display their range, we use the following method ?

  1. Calculate the total number of bits, multiply the sizeof bytes by 8.
  2. Calculate -2^(n-1) for minimum range
  3. Calculate (2^(n-1))-1 for maximum range

Example

This is a C++ program to calculate the range of a signed data type ?

#include <bits/stdc++.h>

#define SIZE(x) sizeof(x) * 8
using namespace std;

void signedRange(int count) {
   int min = pow(2, count - 1);
   int max = pow(2, count - 1) - 1;
   printf("%d to %d", min * (-1), max);
}

int main() {
   cout << "signed char: ";
   signedRange(SIZE(char));
   cout << "\nsigned int: ";
   signedRange(SIZE(int));
   cout << "\nsigned short int: ";
   signedRange(SIZE(short int));

   return 0;
}

Following is the range of data types ?

signed char: -128 to 127
signed int: -2147483648 to 2147483647
signed short int: -32768 to 32767

Calculating Range of Unsigned Data Types

In C++, an unsigned data type is a type of data that only stores non-negative values (positive numbers and zero). So, to display their range, we use the following method.

  1. Calculate the total number of bits, multiply the sizeof bytes by 8
  2. For unsigned data types minimum range is always zero
  3. For compute the maximum range use the 2^n-1

Example

This is a C++ program to calculate the range of a signed data type ?

#include <bits/stdc++.h>

#define SIZE(x) sizeof(x) * 8
using namespace std;

void UnsignedRange(int count) {
   // calculate 2^number of bits 
   unsigned int max = pow(2, count) - 1;
   cout << "0 to " << max;
}

int main() {
   cout << "unsigned char: ";
   UnsignedRange(SIZE(unsigned char));
   cout << "\nunsigned int: ";
   UnsignedRange(SIZE(unsigned int));
   cout << "\nunsigned short int: ";
   UnsignedRange(SIZE(unsigned short));
   return 0;
}

Following is the range of unsigned data types ?

unsigned char: 0 to 255
unsigned int: 0 to 4294967295
unsigned short int: 0 to 65535
Updated on: 2025-05-15T16:01:08+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements