C++-এ int, char, double ইত্যাদি বিভিন্ন ডেটা টাইপ রয়েছে। এই भागে আমরা দেখব কিভাবে প্রোগ্রামেটিক্যালি তাদের আকার জানা যায়।
আমরা ডেটা টাইপের আকার বাইটে পেতে পারি, তাই সেটিকে ৮ দিয়ে গুণ করে বিটে মান পাওয়া যায়। এখন যদি বিটের সংখ্যা n হয়, তবে সাইনড নম্বরের জন্য ন্যূনতম রেঞ্জ হবে –2^(n-1), এবং সর্বোচ্চ রেঞ্জ হবে 2^(n-1) – 1। অনসাইনড নম্বরের জন্য এটা হবে 2^n – 1 কারণ সেখানে নেতিবাচক নম্বর নেই।
উদাহরণ কোড
#include <iostream>
#include <cmath>
#define SIZE(x) sizeof(x) * 8 // বিটে আকার বের করা
using namespace std;
void getRange(string type, int n) {
if(type.compare("SIGNED") == 0) { // সাইনড নম্বরের জন্য নিচের ও উপরের লিমিট ক্যালকুলেট
int min = pow(2, n - 1);
int max = pow(2, n - 1) - 1;
cout << "Range from " << (-1) * min << " to " << max << endl;
} else { // অনসাইনড নম্বরের জন্য ০ থেকে লিমিট ক্যালকুলেট
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));
}আউটপুট
For Signed int: Range from -2147483648 to 2147483647 For Signed float: Range from -2147483648 to 2147483647 For Unsigned int: Range from 0 to 4294967295 For Unsigned short: Range from 0 to 65535 For Signed char: Range from -128 to 127